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;

});
Grant
  • 11,138
  • 32
  • 94
  • 140
  • 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") – Arsh Singh Aug 25 '13 at 09:37
  • What if I wanted to use it outside the template, for example, inside a jQuery ajax call? – Grant Aug 25 '13 at 09: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? – Arsh Singh Aug 25 '13 at 10:21
  • Hi @Arsh, I have updated the question with some example usage. – Grant Aug 25 '13 at 11:55
  • 2
    Do yourself a favor and read this http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background?rq=1 – mfeingold Aug 25 '13 at 14:20
  • @Grant whatever you're trying to do, do you have to use jQuery for it?, are you sure you can't do it with angular's $http ? – Arsh Singh Aug 25 '13 at 15:39
  • @Arsh, I probably could yes. But I have an existing web application using jQuery and would like to start using angular for data binding without having to rewrite all of the jQuery code. I plan on using angular in full for my next application and wont have these problems. – Grant Aug 25 '13 at 22:14
  • @mfeingold thanks I actually read that the other day. – Grant Aug 25 '13 at 22:15

1 Answers1

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.

Community
  • 1
  • 1
Chandermani
  • 42,589
  • 12
  • 85
  • 88