AngularJS工厂采用双向数据绑定

我有一个带有一些绑定变量的角度控制器,以及一个生成数组的工厂(用于在select控件中填充选项):

// Controller MyController
angular.module('users').controller('MyController', ['$scope', 'Authentication', 'MyFactory', 
    function($scope, Authentication, MyFactory) {
        $scope.user = Authentication.user;
        $scope.options = MyFactory.getOptions($scope.user.firstName, $scope.user.lastName);
        ...
    }
    ...
}

// Factory MyFactory
angular.module('users').factory('MyFactory', 
    function() {
        var _this = this;
        _this._data = {
            getOptions: function(firstName, lastName){
                return [
                    firstName + ' ' + lastName,
                    lastName  + ' ' + firstName
                    ...
                ];  
            }
        };
        return _this._data;
    }
);

它第一次运行良好,但不保持控制器和工厂之间的数据同步.

预期的效果是MyFactory.getOptions()参数的更改会修改分配给$scope.options的结果数组.

最佳答案 它是第一次工作,因为你正在调用一个返回一个新数组的函数,然后你的视图只引用该数组,并且从不再次调用该函数.最简单的解决方案是为$scope.user变量添加$scope.$watch,以调用MyFactory.getOptions函数.

// Controller MyController
angular.module('users').controller('MyController', ['$scope', 'Authentication', 'MyFactory', 
    function($scope, Authentication, MyFactory) {
        $scope.user = Authentication.user;
        $scope.options = MyFactory.getOptions($scope.user.firstName, $scope.user.lastName);
        $scope.$watch("user", function(newVal,oldVal,scope) {
            scope.options = MyFactory.getOptions(newVal.firstName, newVal.lastName);
        });
        ...
    }
    ...
}

无论如何都是这样的.可能需要稍微使用语法.

根据您的意见,尝试这样的事情:

// Controller MyController
angular.module('users').controller('MyController', ['$scope', 'Authentication', 'MyFactory', 
    function($scope, Authentication, MyFactory) {
        $scope.user = Authentication.user;
        $scope.options = MyFactory.getOptions($scope, "user");
        ...
    }
    ...
}

// Factory MyFactory
angular.module('users').factory('MyFactory', 
    function() {
        var _this = this;
        _this._data = {
            getOptions: function(scope, property){
                var updateableArray = [];
                function updateArray(user) {
                    //delete all elements of updateableArray
                    updateableArray.clear();
                    //add all the new elements of updateableArray from user argument
                    updateableArray.push(firstName + ' ' + lastName);
                    updateableArray.push(lastName  + ' ' + firstName);
                    ....
                }
                scope.$watch(property, function(newVal,oldVal,watchScope) {
                    updateArray(newVal);
                });
                updateArray(scope[property]);
                return updateableArray;  
            }
        };
        return _this._data;
    }
);

当然有更好的方法来组织它,但希望它足以帮助你理解它.

点赞