3

In my non-angular code I am getting controller object through following code

var controllerElement = angular.element('[ng-controller="' + controllerName + '"]');
var controller = controllerElement.controller();

It was working perfectly until day before yesterday when instead of controller object controller object has some $get.h {}

Following code returns correct controller object but there is a scenario in which angular is throwing exception:

var $controller = injector.get("$controller");
var controller = $controller(controllerName, { $scope: scope });

Could you please help me find figure out what is the problem with former approach i.e. controllerElement.controller();

EDIT: Found another issue with latter approach that it instantiates a new controller object instead of returning the original one associated with the element.

2
  • what is the value returned by controllerElement.length Commented May 20, 2015 at 6:08
  • contrllerElement has length 1 i.e. correct element is found Commented May 20, 2015 at 7:18

1 Answer 1

1

I would strongly recommend not to mix angular code with external JS. Every time you are calling a Controller, it will created indeed a new object, but as far as I understood from your question, you probably want to do some manipulation in it or its data. For persistent data across controllers or states of your application you should use a Service or a Factory, and manipulating it should happen in it, or from a Controller not some random JS somewhere.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.