angular.module('starter.controllers', [])
.controller('controller1',function($scope) {
$scope.function1= function () {
---------------
})
.controller('controller2',function($scope) {
$scope.function1= function () {
//is it possible to access method form controller1 in controller2 like this
controller1.function();
})
我是角度JS的初学者,请指导我完成我的代码。
答案 0 :(得分:2)
在AngularJS中,您可以将服务用于此类事情。
只需使用您想要多次使用的功能创建服务:
.service('myService', function() {
return function() {
//your function1
};
})
然后您将此服务用作依赖项:
.controller('controller2', [
'$scope',
'myService',//say you want the service as second param
function($scope, myService) {
$scope.function1 = function() {
myService();//your function is here
};
}
])
在另一个控制器中也一样:
.controller('controller1', [
'$scope',
'myService',
function($scope,myService) {
$scope.function1 = myService;//bind the service to the scope
}
])