繁体   English   中英

如何获得由AngularJS创建的控制器的实例?

[英]How do I get an instance of a controller that was created by AngularJS?

我有一个基于Angular的应用程序,我这样初始化:

myapp.init = (function () {
  'use strict';

  var angularApp = angular.module('myapp', [])
    .directive('homeIterationDirective', function () {
      return function (scope, element, attrs) {
        var isTopCard = scope.$last ? true : false;
        cards.initSingleSwipe(element.get(0), function (event) {
          // I want to call indexPageController.onSwiped(event) here!
        }, isTopCard);
      };
    })
    .directive('homeDirective', function () {
      return function (scope, element, attrs) {
        cards.initPanel(element, function (event) {
            // I want to call indexPageController.onButtonPressed(event) here!
        });
      };
    });

  angularApp.factory('AjaxService', myapp.services.AjaxService);
  angularApp.controller('IndexPageController', ['$scope', '$http', '$sce', 'AjaxService', myapp.pages.IndexPageController]);

}());

我的控制器如下所示:

myapp.pages.IndexPageController = function ($scope, $http, $sce, MyService) {
  'use strict';

  var somevalue = {};

  this.onSwiped = function (event) {
    doSomethingWith(event, somevalue);
  };

  this.onButtonPressed = function (event) {
    doSomethingWith(event, somevalue);  
  };

};

在2个指令homeIterationDirectivehomeDirective我有2个回调cards.initSingleSwipecards.initPanel 在这些回调中,我想调用控制器的公共方法,但是我没有Angular从IndexPageController创建的可用实例。 我该如何实现?

如果要从另一个地方(可能是另一个控制器)“调用公共方法”,请使用(注入)服务(而不是控制器)。

angularApp.controller('MyController', function ($scope, IndexPageService) {
    IndexPageService.blah();
}));

Controller旨在接收和修改$ scope(添加方法,变量等)。 然后,可以在使用控制器本身的模板(html)内使用$ scope。

如果要在Angular上下文中但在另一个位置调用某些控制器代码,则可能应该将该调用代码移至服务,然后直接调用service方法。

但是,如果您想在Angular上下文之外调用该方法,则可以这样实现:

<div id="foo" ng-controller="IndexPageController">
    <!-- code -->
</div>

现在,您可以编写如下内容:

angular.element(document.getElementById("foo")).scope().blah();

我也认为您应该为此使用服务。 但是,如果仍然需要从另一个调用一个控制器,则可以使用$ controller服务

(function() {
    var app = angular.module('myApp', ['ngRoute']);

    app.config(function ($routeProvider) {
        $routeProvider.when("/first", {
                templateUrl: 'app/view.html',
                controller: 'firstCtrl'
            }).when("/second", {
                templateUrl: 'app/view.html',
                controller: 'secondCtrl'
            })
            .otherwise({
                redirectTo: "/first"
            });
    });

    app.controller('firstCtrl', function ($scope) {

        $scope.name = "first Controller";
        $scope.nameToUpper = function () {
            return $scope.name.toUpperCase();
        }
    });

    app.controller('secondCtrl', function ($scope, $controller) {

        var newScope = $scope.$new();
        $controller('firstCtrl', { $scope: newScope });

        $scope.name = newScope.nameToUpper() + 'from second ctrl';
    });

}())

并且视图是

<div>
    {{name}}
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM