简体   繁体   English

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

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

I have an app based on Angular which I initialize like this: 我有一个基于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]);

}());

My controller looks like this: 我的控制器如下所示:

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);  
  };

};

In the 2 directives homeIterationDirective and homeDirective I have 2 callbacks cards.initSingleSwipe and cards.initPanel . 在2个指令homeIterationDirectivehomeDirective我有2个回调cards.initSingleSwipecards.initPanel Within these callbacks I want to call public methods of my controller but I don't have the instance available that Angular created from IndexPageController . 在这些回调中,我想调用控制器的公共方法,但是我没有Angular从IndexPageController创建的可用实例。 How can I achieve this? 我该如何实现?

Use (inject) a service (and not a Controller) if you want "to call a public method" from another place, possibly from another Controller. 如果要从另一个地方(可能是另一个控制器)“调用公共方法”,请使用(注入)服务(而不是控制器)。

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

Controller is intended to receive and modify a $scope (adding methods, variables..etc). Controller旨在接收和修改$ scope(添加方法,变量等)。 The $scope can than be used inside the template (html) that use the controller itself. 然后,可以在使用控制器本身的模板(html)内使用$ scope。

If you want to call some controller code within the Angular context but in another place, then you should probably move that calling code to a service and then call the service method directly. 如果要在Angular上下文中但在另一个位置调用某些控制器代码,则可能应该将该调用代码移至服务,然后直接调用service方法。

But if you want to call that method outside Angular context then, you can achieve that like this: 但是,如果您想在Angular上下文之外调用该方法,则可以这样实现:

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

Now, you can write something like this: 现在,您可以编写如下内容:

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

I also think you should use a service for this. 我也认为您应该为此使用服务。 But if you still need to call one controller from another you can use $controller service 但是,如果仍然需要从另一个调用一个控制器,则可以使用$ 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';
    });

}())

and view is 并且视图是

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

暂无
暂无

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

相关问题 如何在AngularJS中初始化嵌套控制器? - How do I initialize a nested controller in AngularJS? 给定AngularJS中的模板和控制器实例,如何使用它的控制器实例编译模板? - Given a template and a controller instance in AngularJS, how can I compile the template in a way that it uses my controller instance? Ember.js v1.0.0-rc.1 —如何为以编程方式创建的视图获取/提供控制器? - Ember.js v1.0.0-rc.1 — How do I get/supply a controller for a programmatically created view? 如何使用AngularJS控制器在$ http.get中指定MongoDB键/值参数? - How do I specify MongoDB key/value parameters in an $http.get with an AngularJS controller? 在测试AngularJS控制器时,如何在$ http.get承诺中模拟结果? - How do I mock the result in a $http.get promise when testing my AngularJS controller? AngularJS-如何在状态解析功能中获取状态名称以加载控制器文件? - AngularJS - How do I get the state name inside of state resolve function to load controller files? 如何在AngularJS控制器中获取当前作用域dom-element? - How do I get current scope dom-element in AngularJS controller? 如何在angularJS中获得对指令对象实例的引用? - how do you get a reference to the directive object instance in angularJS? 如何获得模块中定义的angularjs控制器的引用? - How do you get a reference to an angularjs controller defined in a module? 如何访问angularjs中动态创建的字段? - How do I access dynamically created fields in angularjs?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM