父范围变量更改时,在指令中调用函数

时间:2016-09-22 17:48:28

标签: javascript angularjs

当父控制器中的变量值发生变化时,我需要在我的指令中调用一个函数。我尝试添加一个手表(我显然做错了),因为当值发生变化时没有任何反应。这是指令:

    angular.module('ssq.shared').directive('checkboxPicklist', function() {
    return {
        restrict: 'E',
        templateUrl: '/Scripts/app/Shared/directives/checkboxPicklist.html',
        replace: true,
        scope: {
            itemId: '=',
            list: '=',
            nameProp: '=',
            title: '@',
            searchPlaceholder: '@',
            callbackFn: '&',
            callMore: '&',
            clear: '='
        },

        link: function (scope, element, attrs) {
            scope.query = '';
            var parent = scope.$parent;
            var clear = parent.clear;
            scope.$watch(clear, function () {
                if (clear == true) {
                    this.clearAll();
                }
            })
            var child = element.find('.dropdown-menu');
            child.on({
                'click': function (e) {
                    e.stopPropagation();
                }
            });


            var selectedItemFn = function (item) {
                return item.selected;
            };

            scope.getSelectedCount = function () {
                return _.filter(scope.list, selectedItemFn).length;
            };
            scope.loadMore = function () {
                scope.callMore();
            };

            scope.allSelected = function(list) {
                var newValue = !scope.allNeedsMet(list);
                _.each(list, function(item) {
                    item.selected = newValue;
                    scope.callbackFn({ object: item });
                });
            };

            scope.allNeedsMet = function(list) {

                var needsMet = _.reduce(list, function(memo, item) {
                    return memo + (item.selected ? 1 : 0);
                }, 0);
                if (!list) {
                    return (needsMet === 0);
                }
                return (needsMet === list.length);
            };

            function clearAll() {
                _.each(list, function (item) {
                    item.selected = false;
                })
            }
        }

    };
});

这是我试图观察变量的地方:

            var parent = scope.$parent;
            var clear = parent.clear;
            scope.$watch(clear, function () {
                if (clear == true) {
                    this.clearAll();
                }
            })

以下是我的父控制器中的功能,用于更改"清除"

的值
    $scope.clearFilters = function (clear) {

    $scope.clear = true;

    $scope.form.selected.services = [];
    $scope.form.picked.areas = [];
    $scope.form.certified.verifications = [];
    $scope.form.subscribed.subscriptions = [];
    $scope.form.OperatorBusinessUnitID = null;
    $scope.form.OperatorBusinessUnitID = null;
};

我尝试设置一个名为" clearFilter"的属性。并将变量分配给它,但手表仍然没有触发:

            scope.$watch(attrs.clearFilter, function (value) {
                if (value == true) {
                    this.clearAll();
                }
            });

                            <checkbox-picklist data-item-id="'servicesPicklist'"
                                           data-search-placeholder="Search Services"
                                           data-list="services"
                                           data-title="Service(s)"
                                           data-name-prop="'vchDescription'"
                                           data-callback-fn="addService(object)"
                                           call-more="loadMoreServices()"
                                           clear-filter="clear">

                        </checkbox-picklist>

我不确定我是否正确调用该功能。上面的scope.$parent确实从父作用域获取变量的初始值,但一旦变化,它就永远不会更新。

  编辑:我发现的是正常的范围。$ watch(&#39; clear&#39;,function ...)看起来不起作用,因为该指令位于&#34; ssq.shared&#34 ;模块注入我的主模块&#34; myModule&#34; (见下文),所以即使指令所在的页面使用了我的&#39; GeneralSearchCtrl&#39;,我也无法让手表处理位于&#39; GeneralSearchCtrl&#39;中的变量。如果我使用范围。$ parent.clear我可以看到变量的值,但我似乎无法设置它。

我的模块注入代码:

var app = angular.module('myModule', ['ui.bootstrap', 'checklist-model', 'ssq.shared', 'ngAnimate', 'ngTouch', 'ui.grid', 'ui.grid.pagination', 'ui.grid.selection', 'ui.grid.exporter', 'ui.grid.autoResize', 'ui.router', 'cgBusy', 'ui.mask', 'ngFileUpload', 'ngSanitize']);

指令所在的页面使用:

<div ng-app="myModule" ng-controller="GeneralSearchCtrl">

我无法监视GeneralSearchCtrl中的变量。

非常感谢任何帮助!!!!

3 个答案:

答案 0 :(得分:1)

为$ scope值添加监视并调用函数

 <script type="text/javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(demo);
 </script>

答案 1 :(得分:1)

scope.$watch(clear, function () {
  if (clear == true) {
    this.clearAll();
  }
})

This.clearAll()不存在于$ watch函数的范围内。简单地调用clearAll()应该会更好。

signature of the watch function不正确。

scope.$watch('clear', function (new, old) {}

答案 2 :(得分:0)

事实证明,问题在于该指令的定义中scope:{...}阻止了“正常”scope.$watch('clear', function...)的工作。我必须在范围列表中添加清晰的:'=',如下所示:

            replace: true,
        scope: {
            itemId: '=',
            list: '=',
            nameProp: '=',
            title: '@',
            searchPlaceholder: '@',
            callbackFn: '&',
            callMore: '&',
            clear: '='
        },

然后清除=“清除”指令,如:

                            <checkbox-picklist data-item-id="'servicesPicklist'"
                                           data-search-placeholder="Search Services"
                                           data-list="services"
                                           data-title="Service(s)"
                                           data-name-prop="'vchDescription'"
                                           data-callback-fn="addService(object)"
                                           call-more="loadMoreServices()"
                                           clear="clear">

                        </checkbox-picklist>

然后在指令中我必须添加这样的手表才能正常工作:

                scope.$watch('$parent.clear', function (newValue, oldValue) {
                if (newValue == true) {
                 clearAll();
                alert('it works!');
                }
            })

我真的希望这可以帮助别人,因为我很难弄明白。快乐的编码!