$watchCollection id attribute & ng-model

$watchCollection id attribute & ng-model

本文关键字:amp ng-model attribute watchCollection id      更新时间:2023-09-26

我想使用 $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 从角度更改为 ang,则可以使用作用域 virable 作为 id,然后只观察变量。

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

然后您可以使用$watchGroup或$watchCollection一起监视指令 ID 和建模。