有没有定义大量的腕表系列为AngularJS一个整齐的方法吗? [英] Is there a tidy way to define a large watch collection for AngularJS?

查看:113
本文介绍了有没有定义大量的腕表系列为AngularJS一个整齐的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这code:

        $scope.$watchCollection('[config.examId, config.pageType, config.createdBy, config.modifiedBy, config.reference]',
            function (newValue, oldValue) {
                if (typeof newValue !== 'undefined' && typeof oldValue !== 'undefined' && newValue !== oldValue) {
                    _u.putConfigs($scope.config);
                    //$scope.grid.data = null;
                };
             });

现在我有更多的项目添加到集合。有没有一种方法,我可以整齐地Ş$ P $垫这些多行?从我的理解(可能是错的)。该watchCollection必须是一个字符串。

Now I have to add more items to the collection. Is there a way that I can neatly spread these over multiple lines? From what I understand (might be wrong). The watchCollection has to be a string.

推荐答案

嗯,看来你用简单的领域内配置的对象,你可以很容易地修改这个拥有多个手表(可以用这种方式更灵活) 。即使你有复杂的对象,你可以通过使用深标志看着他们:

Well, as looks like you use simple fields inside of your configuration object you can easily modify this to have multiple watch (which can be more flexible in this way). Even if you have complex objects you can watch them by using deep flag:

var app = angular.module('app', []);
app.controller('ConfigCtrl', function($scope, $parse, $log) {
    $scope.config = {};

    // initial configuration
    $scope.watchProperties = ['examId', 'pageType', 'createdBy', 
                          'modifiedBy'];

    // dynamic modifications to the watched properties
    $scope.configureWatchProperties = function() {
        $scope.watchProperties.push('reference');
    }

    $scope.updateConfig = function() {
        // TODO: update config here
        $log.log('config updated:', $scope.config);
    }

    $scope.addWatchProperty = function(context, property, deep) {
        $scope.$watch(function() {
            return $parse(property)(context);
        }, function(newValue, oldValue) {
            if (newValue && newValue !== oldValue) {
                $scope.updateConfig();
            }
        }, deep);
    }

    $scope.configureWatch = function() {
        angular.forEach($scope.watchProperties, function(prop) {
            $scope.addWatchProperty($scope.config, prop);
        });
    }

    $scope.configureWatchProperties();
    $scope.configureWatch();
});

完整的jsfiddle举例:

这篇关于有没有定义大量的腕表系列为AngularJS一个整齐的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆