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?
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)
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.