Answer the question
In order to leave comments, you need to log in
How to solve $watch problem in Angular.js?
I am moving my project to Angular.js, and since the design requires non-standard elements, plugins are used. One of them is the Selecter , to style the look of the drop down menu.
So, I write a directive for this case, it turned out like this:
app.directive("select", ['$timeout', function (timer) {
return {
restrict: "E",
link: function(scope, element, attrs) {
apply = function () {
console.log('установили обработчик');
$(element).selecter('destroy').selecter({
customClass: attrs.color
});
}
init = function () {
apply();
if (attrs.selecterScope) {
console.log('Установили ватч');
scope.$watch(attrs.selecterScope, function () {
console.log('рефрешнули это дело');
timer(apply, 0);
});
}
}
timer(init, 0);
}
};
}]);
<select ng-model="sVersion" color="green" ng-options="c for c in versions" selecter-scope="versions">
<option value="">Выберите версию</option>
</select>
scope.versions = ["1.7.4", "1.7.2", "1.6.4", "1.5.2", "1.4.7"];
Answer the question
In order to leave comments, you need to log in
$watch always idles for initialization. Also in your case, dirty-checking will not work, and therefore it will not detect changes in the array. You either need to set the third argument of the $watch function to true (enables dirty-checking with copying objects and comparing them) or use $watchCollection.
And why not attach ng-model to select instead of these perversions with watchers? In this case, it will be easier to apply an isolated scope to the word in order to avoid problems in the future.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question