javascript - 从 AngularJS 中的 Controller 调用服务

标签 javascript angularjs

我对 AnjularJs 很陌生,所以请耐心等待。在我当前的代码中,各种 Controller 都使用相同的方法。方法已粘贴到每个 Controller 上,这不是一个好的做法。但现在我想在不同 Controller 之间共享这些方法作为 CommonUtility.js 为了做到这一点,我需要提供我在网上查找的服务或工厂。但不确定如何? 如果你能告诉我在这里做什么,请参阅下面的代码。 文件名:Controller.js

(function(){ 
  var somecontrollers = angular.module('angular'); 
  somecontrollers.controller('NameofController', function ($scope, $http) {
    //code
    ..
    ..
    ..
  });
})();

文件名:CommonUtilities.js

var CommonUtilities = angular.module('CommonUtilities', [])
  .service('Collapse', function () {
    this.CollapseTree = function () {
      var name 
      return name
    }
    method2
    method3
    ...
  });

如何在 Controller.js 中添加对 commonUtilities.js 或其方法的引用?任何帮助表示赞赏。 还有一个问题。如何在 CollapseTree 函数中使用 $scope? 谢谢。

最佳答案

这样写就很清楚了:

(function(){ 
  'use strict';

  var somecontrollers = angular.module('angular', ['CommonUtilities']); 
  somecontrollers.controller('NameofController', NameofController);

  NameofController.$inject = ['$scope', '$http', 'Collapse'];

  function NameofController($scope, $http, Collapse) {
    Collapse.CollapseTree();
  });
}();

您只需通过之前提供的名称来引用它即可。另外,请务必包含包含您的服务的模块。

您不能在服务中使用$scope$scope 严格用于 Controller ,作为在 View 中引用方法和变量的一种方式。

关于javascript - 从 AngularJS 中的 Controller 调用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42448989/

相关文章:

javascript - Angular js - 在 ng-repeat 内使用 ng-checked 多次触发函数

java - 如何从同一模型中的不同表中检索对象列表?

javascript - 为什么 $routeParams 未定义?

javascript - 有什么方法可以获取或计算 ScrollView 的速度吗?

javascript - 如何使用 Protractor 在下拉列表中随机获取元素?

javascript - jeditable:使用选择时出现错误

ruby-on-rails - Angular $http 和 Rails 4 参数

javascript - Angularjs ng-bind-html-unsafe 替换

javascript - Javascript 模板框架的基准是什么?

javascript - IE 丢弃 vbscript,但 activex 终端服务控制 msrdp.ocx 仅适用于 vbscript