角度指令中的ng-repeat(ng-repeat in angular directive)
我正在尝试创建一个带有一些额外功能的自定义选择指令。
.directive('singleSelect',function(){ restrict:'A' scope:{ model:'=' } link:function(elem,scope,attrs){ elem.bind('click',function(){ scope.vModel=model.slice(0,20); }); controller:function($scope) { //some more manipulation with model and assign to vModel } template:'<ul><li ng-repeat="item in vModel"></li><ul>' });问题是我将值赋给vModel但它没有在模板中更新。
I am trying to create a custom select directive with some extra functionality.
.directive('singleSelect',function(){ restrict:'A' scope:{ model:'=' } link:function(elem,scope,attrs){ elem.bind('click',function(){ scope.vModel=model.slice(0,20); }); controller:function($scope) { //some more manipulation with model and assign to vModel } template:'<ul><li ng-repeat="item in vModel"></li><ul>' });The problem is that I am assigning the value to vModel but it is not getting updated in the template.
最满意答案
这是因为您正在jQuery选择器中更新范围变量。 您需要使用$ scope。$ apply来启动摘要周期,这将更新您的模型。
尝试这个:
.directive('singleSelect',function(){ restrict:'A' scope:{ model:'=' } link:function(scope, elem, attrs){ elem.bind('click',function(){ scope.$apply(function(){ scope.vModel=model.slice(0,20); }) }); controller:function($scope) { //some more manipulation with model and assign to vModel } template:'<ul><li ng-repeat="item in vModel"></li><ul>' });This is happening because you are updating your scope variable inside a jQuery selector. You need to use $scope.$apply to start the digest cycle which will update your model.
Try this:
.directive('singleSelect',function(){ restrict:'A' scope:{ model:'=' } link:function(scope, elem, attrs){ elem.bind('click',function(){ scope.$apply(function(){ scope.vModel=model.slice(0,20); }) }); controller:function($scope) { //some more manipulation with model and assign to vModel } template:'<ul><li ng-repeat="item in vModel"></li><ul>' });更多推荐
发布评论