Timo Ernst
Timo Ernst

Reputation: 15983

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:

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. 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. How can I achieve this?

Upvotes: 0

Views: 116

Answers (3)

Chintana Meegamarachchi
Chintana Meegamarachchi

Reputation: 1820

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

(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>

Upvotes: 0

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

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.

But if you want to call that method outside Angular context then, you can achieve that like this:

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

Now, you can write something like this:

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

Upvotes: 0

obe6
obe6

Reputation: 1891

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). The $scope can than be used inside the template (html) that use the controller itself.

Upvotes: 1

Related Questions