AngularJS - make model variable available to jQuery?

I am just starting with AngularJS and am trying to figure out how to easily reference (bind?) scope variables from outside the Angular controller.

Simple code:

<div ng-controller="Ctrl">
  <label>Name:</label>
  <input type="text" ng-model="yourNameInput" placeholder="Enter a name here">
  <input type="button" onClick="console.log(inputName);">
  <hr>
  <h1 ng-bind-template="Hello, {{yourNameInput}}"></h1>
</div>

How would I bind {{yourNameInput}} to inputName var that will be available to the rest of my application? There's one ugly way I managed to do that:

$scope.change = function() { inputName = $scope.yourNameInput; }

and then:

<... ng-change = "change()">

Anything more elegant?

Answers


You can inject $window into your controller and make it available on the scope. See example.

function Ctrl($scope, $window) {
    $scope.window = $window;
}‚Äč

...

<input type="text" ng-model="yourNameInput" placeholder="Enter a name here" ng-change="window.yourName = yourNameInput">

For broader use you can make it available on the $rootScope. See another example.

angular.module('myApp', [])
    .run(function($rootScope, $window){
        $rootScope.window = $window;
    });

Also you can see Call Angular JS from legacy code.

For console.log() you can use

<input type="button" onClick="console.log('{{yourNameInput}}');" value="Log">

See example.

If you want to debug AngularJS application you can use AngularJS Batarang (textual description and source code)


Need Your Help

What should I replace small structs with in Java?

java oop struct maps idiomatic

I am building a mapping app in Java, and I have a question about passing around small objects. Say I want to represent the area that the window is showing as a rectangle, and I want to query which ...

How to Get SoundCloud RSS Download Stats via API?

api rss soundcloud

With SoundCloud's recent update showing RSS Downloads as a separate statistic, I am not able to find a way to get this stat via the API.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.