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();
})
我是 Angular JS 的初学者,请指导我完成我的代码。
最佳答案
在 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 中也是如此:
.controller('controller1', [
'$scope',
'myService',
function($scope,myService) {
$scope.function1 = myService;//bind the service to the scope
}
])
关于javascript - AngularJS中 Controller 2中 Controller 1的访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28165534/