javascript - AngularJS中 Controller 2中 Controller 1的访问方法

标签 javascript angularjs

    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/

相关文章:

javascript - 如何从术语存储 SharePoint Online 检索多值分类字段

javascript - vue-awesome-swiper 和回调函数

javascript - 如何从下拉列表中删除除从另一个下拉列表中选择的值之外的所有值

javascript - 如何在 AngularJS 中有条件地应用指令?

javascript - 单击不导航时,超链接在 ckeditor 中不起作用

JavaScript 预分配数组 Uncaught RangeError : Invalid Array Length

javascript - 当用户输入逗号时,Angularjs 会破坏标签

javascript - 使用 Twitter Bootstrap 3.0 的模态不显示在手机上

javascript - ul 中的交换列表和事件元素位置保持不变

javascript - 动态$http GET方法分配多个变量不同的数据