我有一个带有一些绑定(bind)变量的 Angular Controller ,以及一个产生数组的工厂(用于填充选择控件中的选项):
// 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;
}
);
它第一次运行良好,但无法在 Controller 和工厂之间保持数据同步。
预期效果是
MyFactory.getOptions()
的参数发生变化。修改分配给 $scope.options
的结果数组.
最佳答案
它第一次工作,因为您正在调用一个返回新数组的函数,然后您的 View 只引用该数组,并且永远不会再次调用该函数。最简单的解决方案是添加 $scope.$watch
为您的$scope.user
调用 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;
}
);
当然有更好的方式来组织它,但希望它足以帮助你理解这个想法。
关于AngularJS工厂双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26425494/