I'm confused about the connection between scope.ngModel
and controller.$viewValue
/controller.$modelValue
/controller.$setViewValue()
. I'm specifically unsure of the purpose of the latter three. Take a look at this jsfiddle:
<input type="text" ng-model="foo" my-directive>
and:
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);
}
}
});
Using the following controller:
function MyCtrl($scope, $timeout) {
$scope.foo = 'ahha';
$timeout(function () {
$scope.foo = "good";
}, 1000);
}
The output appears as follows:
(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
Initially, controller.$viewValue
did not match the value of foo
. Also, the use of
controller.$setViewValue("boorb")
didn't affect scope.ngModel
, and the update wasn't reflected in the HTML. It seems like there's no direct relationship between scope.ngModel
and controller.$viewValue
. For any intended action, it appears that using scope.ngModel
along with watching those values would suffice. What is the benefit of utilizing controller.$viewValue
and controller.$modelValue
, or ensuring they are in sync with scope.ngModel
?