我有一个带有一些绑定变量的角度控制器,还有一个产生数组的工厂(用于填充选择控件中的选项):
// 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.$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;
}
);
当然,有一种更好的组织方式,但希望它足以帮助您理解。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句