Tho*_*rin 3 javascript angularjs angularjs-ng-repeat angular-directive
当我想要一个显示事物列表的指令时,我一直在突然对准角度,但我希望它足够通用以处理多个类型/形状的对象.举个简单的例子,我可以说
<select ng-options="person.id by person in people" ng-model="selectPerson">
<option>
{{person.name}}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
(请记住,这是一个简单的例子,这个简单的东西可能不会从指令中受益)
现在我想把它变成一个名为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
}
}
});
Run Code Online (Sandbox Code Playgroud)
但接下来我就开始在嘴里呕吐了一下
//html template _coolselect.html
<select ng-model="selectedItem" ng-options="item[scope.idProperty] by item in items">
<option>
{{item[scope.displayProperty]}}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
说实话,我甚至不确定这是否有效.我已经看到了ui-select通过使用外部范围所做的事情.也许这是要走的路? https://github.com/angular-ui/ui-select/blob/master/dist/select.js#L892
但后来我觉得我需要喜欢转换,就像ui-select那样.是不是有更简单的方法?我是否试图对泛型指令?这不是其他人遇到的问题吗?
编辑:最后它看起来像这样理想.
<cool-select repeat="person.id by person in people" display-property="name"></cool-select>
Run Code Online (Sandbox Code Playgroud)
请参阅下面的演示如何将每个对象从数组传递到ng-repeater中的指令
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope) {
$scope.people = [{
name: "John"
}, {
name: "Ted"
}]
});
app.directive('user', function() {
return {
restrict: 'EA',
template: "<p>*name:{{user.name}}</p>",
scope: {
user: '='
},
link: function(scope, element, attr) {
console.log(scope.user);
}
};
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
<div ng-repeat="person in people" user="person"></div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8999 次 |
| 最近记录: |