E
E
ErickSkrauch2014-03-12 12:58:41
JavaScript
ErickSkrauch, 2014-03-12 12:58:41

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);
        }
    };
}]);


The timer is needed so that the data is first rendered in:
<select ng-model="sVersion" color="green" ng-options="c for c in versions" selecter-scope="versions">
    <option value="">Выберите версию</option>
</select>

And only after that the plugin was applied.

The error lies in the fact that $watch behaves completely incomprehensibly. First, it immediately fires at the time of installation, regardless of whether the data has changed or not. Second, it does not catch further changes to the variable.

The variable stores a regular array of the form:
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

1 answer(s)
S
Sergey, 2014-03-12
@ErickSkrauch

$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 question

Ask a Question

731 491 924 answers to any question