If this has already been explained or is being discussed somewhere, I'm sorry, but I could not find this exact problem being discussed anywhere.
So, I have an angular directive with one data binding myvar (= or @ does not matter). The value from the data binding is used in the directive: scope.myvarStr = scope.myvar + 'somestring'. Then I bind myvarStr in the template.
Since scope.myvarStr needs to be changed when scope.myvar changes, I used $ watch ('myvar', function (...)) to view the value and update scope.myVarStr when necessary. In the clock function, I put the classic if (newValue === oldValue) return;
The problems started the first time $ watch, and both values were equal; that view has not been updated. I could easily see that from console.log (scope.myvar) in the first line of the link function, that scope.myvar was undefined (or "dependent on the type of binding"), and that the value was changed to something else when I made console.log in hours $.
I figured out for an hour or so, and found this: https://github.com/angular/angular.js/issues/11565
However, this question was not discussed anywhere, so I searched googled more and came across $ observ AngularJS: Difference between the $ observ and $ watch methods
When I switched from $ watch to $ observ, all my problems disappeared, and I can still use if (newValue === oldValue) return;
(function(directives) {
'use strict';
directives.directive('someDir', [function() {
return {
restrict: 'E',
scope: {
myvar: '='
},
template: '<p>{{myvarStr}}</p>',
link: function(scope, el, attrs) {
function toString() {
if (scope.myvar < 1000) {
scope.myvarStr = scope.myvar;
} else {
scope.myvarStr = scope.myvar/1000 + 'k';
}
}
toString();
scope.$watch('myvar', function(newValue, oldValue) {
console.log("changed", newValue, oldValue)
if (newValue == oldValue) return;
toString();
},true);
}
};
}]);
}(angular.module('myApp.directives')));
. , $watch, . , , - , , $watch , (, , , "" ).