我正在使用ng-repeat
并使用类似于以下内容设置模型
<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)
.directive("myDirective", function () {
return {
require: 'ngModel',
link: function(scope, lElement, attrs, model) {
console.log(attrs.ngModel); // will log "thing"
}
}
})
答案 1 :(得分:2)
如果要绑定范围值,则可以使用&#39; =&#39;在一个孤立的。这将出现在您的指令范围内。要阅读ng-model
指令,您可以使用=ngModel
:
.directive("myDirective", function () {
return {
scope: {
model: '=ngModel'
}
link: function(scope) {
console.log(scope.model.name); // will log "thing"
}
}
});
答案 2 :(得分: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);
});
});
}
}
});