在 AngularJS + Rest API 中构建一个简单的控制面板。
构建了一个简单的工厂,它发出 API 请求 (GET, POST)
并将必要的数据返回到成功回调。由于 API 可以返回服务器端表单字段错误,因此需要处理返回数据并更改 $scope
。
我无法在工厂内构建处理/更改 $scope
,因为工厂没有(也不应该)访问该范围。我不想在成功回调中处理/应用,因为它会重复(每个 API 请求一次)。
解决这个问题的最佳“Angular 方式”是什么?
一个可能的解决方案是让一个函数存在于 Angular 应用程序之外,然后将 $scope 和必要的数据传递给它。
这感觉像是一个糟糕的变通办法(见下文)。
myApp.controller("saveForm", ["$scope", "api", function($scope, api), function() {
...
$scope.submit = function() {
api("POST", url, $scope.data, function(data) {
//onSuccess
processData($scope, data);
});
}
...
}]);
myApp.factory('api', ['$http', function($http) {
return function(method, url, input, success, error) {
//Retrieve data from API. Note that factory DOES NOT have access to $scope.
$http(...
}
}]);
var processData = function(scope, data) {
angular.forEach(data, function(value, key)) {
scope....
}
}
最佳答案
不确定我是否明白你的意思,但你可以以混合方式扩展 Controller :
基础 Controller
(function() {
'use strict';
angular.module('Base', []);
function BaseController($scope, <injectables>, that) {
that.mixin1 = function() {
};
that.mixin2 = function(arg1, arg2) {
};
}
angular.module('Base').controller('BaseController',
['$scope', '...', BaseController]);
})();
继承 Controller
(function() {
'use strict';
angular.module('Derived', ['Base']);
function DerivedController($scope, $controller, ...) {
$controller('BaseController', {
'$scope' : $scope,
...
'that' : this
});
// this.mixin1
// this.mixin2
}
angular.module('Derived').controller('DerivedController',
['$scope', '$controller', '...', DerivedController]);
})();
请注意,您使用 Angular 的 $controller
服务来混合功能。
关于javascript - 可用于多个 Controller 的 AngularJS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25983035/