【发布时间】:2015-03-30 03:19:37
【问题描述】:
当我想要一个显示事物列表的指令时,我一直在思考角度问题,但我希望它足够通用以处理多种类型/形状的对象。举个简单的例子,假设我有
<select ng-options="person.id by person in people" ng-model="selectPerson">
<option>
{{person.name}}
</option>
</select>
(请记住,这是一个简单的示例,这么简单的东西可能不会从指令中受益)
现在我想把它变成一个叫做cool-select的通用指令 我可能会尝试在我的 js 中做这样的事情
//directive coolselect.directive.js
angular.module('mycoolmodule',[]).directive('coolSelect',function(){
return {
restrict:'E',
templateUrl:'js/coolselectdirective/_coolselect.html',//html from example above
scope:{
items:'=',
displayProperty:'@',
idProperty:'@',
selectedItem:'='
},
link:function(scope,element){
//do cool stuff in here
}
}
});
但接下来就是我开始在嘴里吐一点东西的地方
//html template _coolselect.html
<select ng-model="selectedItem" ng-options="item[scope.idProperty] by item in items">
<option>
{{item[scope.displayProperty]}}
</option>
</select>
老实说,我什至不确定这是否适用于 Angular。我已经看到 ui-select 通过使用外部作用域做了什么。也许这就是要走的路? https://github.com/angular-ui/ui-select/blob/master/dist/select.js#L892
但是我想我需要像 ui-select 一样喜欢 transclude。 没有更简单的方法吗?我是否试图制定通用指令?这不是其他人遇到的问题吗?
编辑: 最后,它看起来像这样是理想的。
<cool-select repeat="person.id by person in people" display-property="name"></cool-select>
【问题讨论】:
-
您应该将指令用作元素并将其用作类吗?当你把restrict E改成C时,你就可以把它当作一个类来使用了。
-
对不起类,只是为了表明有与此元素关联的自定义样式。
-
我把课拿出来让它更清楚
标签: javascript angularjs angularjs-ng-repeat angular-directive