Alf*_*TeK 4 angularjs angular-directive
我在 input=text 标签上使用了一个属性指令,如下所示:
<input type="text" ng-model="helo" my-directive />
Run Code Online (Sandbox Code Playgroud)
在我的指令中,我试图使用 ngModelController 来保存我输入的初始值,在这种情况下是与其关联的 ng-model 的值。
指令是这样的:
app.directive('myDirective', function () {
return {
restrict: "A",
scope: {
},
require: "ngModel",
link: function (scope, elm, attr, ngModel) {
console.log("hi");
console.log(ngModel.$modelValue);
console.log(ngModel.$viewValue);
console.log(elm.val());
}
}
});
Run Code Online (Sandbox Code Playgroud)
问题是 ngModel.$modelValue 是空的,可能是因为在指令初始化时 ngModel 还没有用正确的值更新。那么,如何在我的指令中存储在我的输入字段上设置的第一个值?
如何正确访问 ngModel.$modelValue 以使其具有正确的值?
我也会感谢解释为什么这不起作用,因为我没有通过阅读文档清楚地理解这一点。
Plunkr 完整示例:http ://plnkr.co/edit/QgRieF
$watch在 myDirective 中使用
app.directive('myDirective', function () {
return {
restrict: "A",
scope: {
},
require: "ngModel",
link: function (scope, elm, attr, ngModel) {
var unwatch = scope.$watch(function(){
return ngModel.$viewValue;
}, function(value){
if(value){
console.log("hi");
console.log(ngModel.$modelValue);
console.log(ngModel.$viewValue);
console.log(elm.val());
unwatch();
}
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
对于演示,请参阅此链接
| 归档时间: |
|
| 查看次数: |
1143 次 |
| 最近记录: |