【发布时间】:2015-11-04 19:48:03
【问题描述】:
我不清楚scope.ngModel 和controller.$viewValue/controller.$modelValue/controller.$setViewValue() 之间的关系是什么,具体来说,后三者的意义是什么。例如,见this jsfiddle:
<input type="text" ng-model="foo" my-directive>
和:
myApp.directive('myDirective', function($timeout) {
return {
require: 'ngModel',
restrict: 'A',
scope: { ngModel: '=' },
link: function (scope, element, attrs, controller) {
function log() {
console.log(scope.ngModel);
console.log(controller.$viewValue);
console.log(controller.$modelValue);
}
log();
controller.$setViewValue("boorb");
log();
scope.$watch('ngModel', function (val) {
console.log("val is now", val);
});
$timeout(function () {
log();
}, 2000);
}
}
});
控制器是:
function MyCtrl($scope, $timeout) {
$scope.foo = 'ahha';
$timeout(function () {
$scope.foo = "good";
}, 1000);
}
输出是:
(index):45 ahha
(index):46 NaN
(index):47 NaN
(index):45 ahha
(index):46 boorb
(index):47 boorb
(index):53 val is now ahha
(index):53 val is now good
(index):45 good
(index):46 boorb
(index):47 boorb
controller.$viewValue 最初不是foo 变量的值。此外,controller.$setViewValue("boorb") 根本没有影响scope.ngModel,更新也没有反映在 HTML 中。因此,scope.ngModel 和controller.$viewValue 之间似乎没有关系。似乎对于我想做的任何事情,我都会使用scope.ngModel,并观察这些值。使用controller.$viewValue 和controller.$modelValue 或使用scope.ngModel 让它们保持最新有什么意义?
【问题讨论】:
-
有帮助的:radify.io/blog/…
标签: javascript angularjs angularjs-directive angular-ngmodel