1

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?

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
MarkL
  • 8,770
  • 7
  • 26
  • 27

2 Answers2

4

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)

Community
  • 1
  • 1
Artem Andreev
  • 19,942
  • 5
  • 43
  • 42
  • Thanks. All of those examples worked. If I could only figure out how to use jQuery validation now w/AngularJS, everything would be great. – MarkL Sep 09 '12 at 13:50
  • @MarkL you could try using AngularUI which provides an alternate way to perform form validation http://angular-ui.github.com/ – Scott Sword Mar 03 '13 at 23:44
1

Well I guess you wouldn't expect your outside world would update automatically when your model changes. Rather, you may do a pull to your model.

I don't like the idea of syncing your model data with a global variable. If I were you, I'd do this

console.log($("[ng-controller=Ctrl]").scope().yourNameInput);

which every place in the outside world is required to have access to the model.

Abdul Munim
  • 18,869
  • 8
  • 52
  • 61