0

我使用ng-repeat並設置與之類似以下當我需要ngModel控制器如何訪問

<div ng-repeat="thing in things" ng-model="thing" my-directive> 
    {{thing.name}} 
</div> 

模型中的模型控制器的屬性,然後在我的指令,它看起來像這樣

.directive("myDirective, function() { 
    return { 
     require: 'ngModel', 
     link: function(scope, lElement, attrs, model) { 

     console.log(model.name);// this gives me 'NAN' 
     } 
    } 
}) 

我的問題是如何訪問模型中的值?我試過model.$modelValue.name,但沒有奏效。

+0

爲什麼下來投票? –

回答

2

如果你想綁定一個作用域值,那麼你可以在孤立的地方使用'='。這將出現在您的指令範圍內。要閱讀ng-model指令,你可以使用=ngModel

.directive("myDirective", function() { 
    return { 
     scope: { 
      model: '=ngModel' 
     } 
     link: function(scope) { 

     console.log(scope.model.name); // will log "thing" 
     } 
    } 
}); 
2
.directive("myDirective", function() { 
    return { 
     require: 'ngModel', 
     link: function(scope, lElement, attrs, model) { 

     console.log(attrs.ngModel); // will log "thing" 
     } 
    } 
}) 
0

如果你的指令不具有隔離或子範圍,那麼你可以這樣做:

.directive('someDirective', function() { 
    return { 
     require: ['^ngModel'], 
     link: function(scope, element, attrs, ctrls) { 
      var ngModelCtrl = ctrls[0]; 
      var someVal; 
      // you have to implement $render method before you can get $viewValue 
      ngModelCtrl.$render = function() { 
       someVal = ngModelCtrl.$viewValue; 
      }; 
      // and to change ngModel use $setViewValue 
        // if doing it in event handler then scope needs to be applied 
      element.on('click', function() { 
       var val = 'something'; 
       scope.$apply(function() { 
        ngModelCtrl.$setViewValue(val); 
       }); 
      }); 
     } 
    } 
}); 
相關問題