Javascript AngularJS中控制器2中控制器1的访问方法
我是AngularJS的初学者,请指导我完成我的代码。在AngularJS中,您使用服务来完成这类工作 只需使用您想要多次使用的功能创建一个服务:Javascript AngularJS中控制器2中控制器1的访问方法,javascript,angularjs,Javascript,Angularjs,我是AngularJS的初学者,请指导我完成我的代码。在AngularJS中,您使用服务来完成这类工作 只需使用您想要多次使用的功能创建一个服务: angular.module('starter.controllers', []) .controller('controller1',function($scope) { $scope.function1= function () { --------------- }) .controller('c
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();
})
然后将此服务用作依赖项:
.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
};
}
])
不,您不能在第二个控制器中访问它,但如果您希望这样的东西共享函数,b/w控制器会创建一个角度服务。此外,如果您需要一个具有多个函数的服务,只需返回一个带有函数变量的对象,并从任何地方调用它们,如
myService.niceFunction()
。@DonJuwe当然,如果他在其他地方也使用了其他功能,那么它就更聪明了
.controller('controller1', [
'$scope',
'myService',
function($scope,myService) {
$scope.function1 = myService;//bind the service to the scope
}
])