0

I have some simple Angular.js code that I do not understand.

HTML:

<div ng-controller="MyCtrl">
  Hello, {{name}}!
</div>

JavaScript:

var myApp = angular.module('myApp',[]);

var controller = myApp.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.name = 'Superhero';
}]);

alert(controller.name);

The HTML directive produces what I would expect: "Hello, Superhero!" is rendered to the page. But the alert box is perplexing. I would expect it to show the string "Superhero", or perhaps the controller's name "MyCtrl", but what it actually shows is the module's name "MyApp". Why? What would I need to pass to alert to show the name assigned to the controller's scope (i.e. "Superhero") or the name of the controller itself (i.e. "MyCtrl")?

(N.B. I did try the documentation but it didn't help me untangle why the controller is reporting the module's name instead of its own.)

2
  • 2
    myApp.controller() returns the module so you can chain registration together Commented Dec 11, 2014 at 15:25
  • That makes sense of what's happening. How do I programmatically access the controller I just created? Plus where is the documentation foe myApp.controller()? The documentation I was looking at suggests it returns the controller, but that's probably the wrong page Commented Dec 11, 2014 at 15:28

1 Answer 1

1

You want to access angular's code from a legacy code.

the way I do it is with angular.element:

<div id="myDiv" ng-controller="MyCtrl">
  Hello, {{name}}!
</div>   

var theScope = angular.element(getElementById('myDiv')).scope();
alert(theScope.name);
Sign up to request clarification or add additional context in comments.

6 Comments

So in my code the way to get the controller I just created is to search the DOM for it? That'll work (thanks) but seems odd.
It's not that odd when you think of it this way - the dom element is the only one who can really behave as you wish because the controller itself can be used among many other dom elements @dumbledad
But isn't that exactly why you might want access to the controller itself?
I can't really tell because I'm not sure what is you intention when accessing it from legacy code. What I do know is that a single controller can be launched multiple times and than your 'name' scope variable has multiple values. only a DOM element that initiate the CTRL has a single value for name
That helps, thanks. I'm not sure what you mean by 'legacy code' (I usually parse that as code from a previous language, project, or version). What do you mean by 'legacy code' here?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.