Search code examples
javascriptangularjsangularjs-directiveangular-directive

$watchCollection id attribute & ng-model


I would like to use $watchCollection in order to track 2 things in my directive.

  1. it's ng-model.

  2. it's the id attribute.

I know how to watch each one separately.

return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            options: '=',
            model: '=ngModel'
        },
        link: function ($scope, $el, $attrs) {
            scope = $scope;
            $scope.$watch(
                function () {
                    return $el[0].id;
                },
                function (elementId) {
                    $('#' + elementId).on('switch-change', function () {
                        scope.model[this.id] = $(this).find('input').is(':checked');
                        $scope.$apply();
                    });

                    $('#' + elementId)['bootstrapSwitch']();
                    $('#' + elementId).bootstrapSwitch('setOnLabel', _($('#' + elementId).attr('data-on-label')));
                    $('#' + elementId).bootstrapSwitch('setOffLabel', _($('#' + elementId).attr('data-off-label')));
                });
            $scope.$watchCollection('model', function(newval){
                if(typeof newval !== 'undefined' && !$.isEmptyObject(newval)){
                    // do some stuff here
                }
            });
        }
    }

But I would like to get all the variable in the same function.. Thank you


Solution

  • If you change the id from angular then you can use a scope virable as the id and then just watch the var.

    <div id="{{directiveId}}"></div>
    

    then you can use $watchGroup or $watchCollection to watch directiveId and model together.