簡體   English   中英

角度指令中的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但它沒有在模板中更新。

這是因為您正在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>'
});

注意,鏈接函數中的參數按順序排列如下:link:function(scope,elem,attrs)

嘗試使用$ apply方法:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM