我想从作为属性放置在 input
元素上的指令内部观看模型:
<input id="mymodel_headline" name="mymodel[headline]"
ng-model="mymodel.headline" sps-watch="true" type="text">
如果我正确阅读文档,我应该能够通过链接函数的 attrs
参数或要求 ngModel
获取该值。然而,这些方法都不起作用:
app.directive('spsWatch', function() {
return {
require: "ngModel",
link: function(scope, element, attrs, ngModel) {
console.log("directive called");
console.log(attrs.ngModel);
scope.$watch(scope[attrs.ngModel], function(result) {
console.log("watching via attribute");
console.log(result);
});
scope.$watch(ngModel, function(result) {
console.log("watching via ngModel");
console.log(result)
});
}
};
});
它们似乎只在首次创建指令时运行一次。
最佳答案
您可以通过ngModel.$viewValue
检索模型的值。从 $watch
表达式中的匿名函数返回该值,模型中的更改将触发您的 $watch
函数:
scope.$watch(function () {
return ngModel.$viewValue;
}, function(result) {
console.log("watching via ngModel");
console.log(result)
});
关于javascript - 从属性指令中观察元素的 ngModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24327051/