[英]Why doesn't this angular select wrapper directive work?
我正在尝试制作一个使用硬编码列表环绕select
的指令
var app = angular.module('dirApp',[]); app.directive('dir', [function(){ return{ restrict: 'E', template: "<select ng-options='x for x in vm.arr'></select>", controllerAs: 'vm', link: function(scope) { scope.arr=["a", "b"]; } }; }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="dirApp"> <dir></dir> </div>
如您所见,由于某种原因,列表没有填充值。 我究竟做错了什么?
您必须将数据放入Controller ,然后将ngModel添加到模板中。
指示
(function(){
function dir() {
return{
restrict: 'E',
template: "<select ng-model='vm.x' ng-options='x for x in vm.arr'></select>",
controllerAs: 'vm',
controller: function() {
var vm = this;
vm.arr = ["a", "b"];
vm.x = vm.arr[0]
}
};
}
angular
.module('app')
.directive('dir', dir);
})();
你忘了指定ng-model="currentValue"
在你的选择 ; 没有它, 选项将不会初始化。 另外,如果要使用controllerAs引用控制器,则可能需要定义控制器:
controller: function () {
this.arr = ["a", "b"];
},
或者您可以将数组直接放在指令的范围内。 这是您指令的一些更新:
myApp.directive('dir', function () {
return {
restrict: 'E',
template: "<select ng-model='crrValue' ng-options='x for x in vm.arr'></select><div ng-repeat='item in arr'>{{item}}</div>",
controller: function () {
this.arr = ["a", "b"];
},
controllerAs: 'vm',
link: function (scope) {
scope.arr = ["c", "d"]
}
};
});
您会注意到div和select之间的区别。
希望这对任何人有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.