我对 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/