ng按角度方向重复

ng-repeat in angular directive

本文关键字:方向 ng      更新时间:2023-09-26

我正在尝试创建一个带有一些额外功能的自定义select指令。

.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,但它没有在模板中更新。

之所以会发生这种情况,是因为您正在更新jQuery选择器中的范围变量。您需要使用$scope$申请以启动摘要周期,该周期将更新您的模型。

试试这个:

.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>'
});

注意,链接函数中的参数按如下顺序排列:链接:函数(范围、元素、属性)

尝试使用$apply方法:

elem.bind('click',function(){
 scope.$apply(function(){
        scope.vModel=model.slice(0,20);
      }); 
});

捕捉点击事件的最佳方法是使用angular ng-click指令:https://docs.angularjs.org/api/ng/directive/ngClick