javascript - 可用于多个 Controller 的 AngularJS 函数

标签 javascript angularjs

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/

相关文章:

javascript - 通过javascript编辑后保存,并调整大小问题

javascript - 如何生成最小尺寸的 Javascript 对象?

javascript - 为什么控制台消息显示多次?

javascript - JS 范围/引用问题

html - 如何使用 html 和 css 创建带有 Ul 和 li 元素的给定水平下拉菜单

javascript - 我如何测量 React 16 中浪费的渲染?

javascript - ng-click + ng-repeat 并尝试更改面板样式

java - Spring 安全不适用于 angularJS

javascript - 将 angularJS 与 requireJS 一起使用 - 无法读取未定义的属性 'module'

javascript - Jasmine SpyOn haveBeenCalled 函数引用不起作用( Angular )