角度指令中的ng

编程入门 行业动态 更新时间:2024-10-26 22:29:50
角度指令中的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>' });

更多推荐

本文发布于:2023-08-06 18:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1452895.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指令   角度   ng

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!