$watchCollection id 属性和 ng-model

$watchCollection id attribute & ng-model

我想使用 $watchCollection 来跟踪指令中的 2 件事。

  1. ng-model

  2. 这是 id 属性。

我知道如何分别观看。

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

但我想在同一个函数中获取所有变量.. 谢谢

如果您将 id 从 angular 更改为 id,那么您可以使用范围 virable 作为 id,然后只观察 var。

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

然后你可以使用$watchGroup 或$watchCollection 来同时监视directiveId 和model。