2

I have been following some of the introductory AngularJS tutorials and they start off by showing how easy it is to get started.

They say all you have to do is define ng-app and then use the example of an input with ng-model="name" and then show that string as you type using {{name}}.

My question is, is it possible to access and read the 'name' property without having to define a controller and read it using $scope.name?

For example..

$(function () {

    var name = ?.name;

});
8
  • 1
    You can just use {{ name }} anywhere in the template because you defined it in the rootscope (unless it is overridden by the local scope, so it's safer to use ng-model="something.name") Commented Aug 25, 2013 at 9:37
  • What if I wanted to use it outside the template, for example, inside a jQuery ajax call? Commented Aug 25, 2013 at 9:41
  • Where are you making the jQuery ajax call ? is it inside an angular controller? can you explain what you're trying to do or mabe post some code? Commented Aug 25, 2013 at 10:21
  • Hi @Arsh, I have updated the question with some example usage. Commented Aug 25, 2013 at 11:55
  • 2
    Do yourself a favor and read this stackoverflow.com/questions/14994391/… Commented Aug 25, 2013 at 14:20

1 Answer 1

4

Well as it turns out, setting ng-model without a ng-controller defined at any parent level creates the item on the $rootScope.

What it also means that whereever $rootScope dependency can be injected you can get access to variable you define in the view.

See my fiddle here

Update: Based on the question update. You can access the scope outside from angular using something like

angular.element(domElement).scope()

and the access the variable. See this answer. But please avoid as much as possible.

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

Comments

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.