Simple question: How can I set a scope value in html, to be read by my controller?
var app = angular.module('app', []); app.controller('MyController', function($scope) { console.log($scope.myVar); });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app='app'> <div ng-controller="MyController" app-myVar="test"> {{myVar}} </div> </div>
JSFiddle: http://jsfiddle.net/ncapito/YdQcX/
ng-init
does not work when you are assigning variables inside loop. Use {{myVariable=whatever;""}}
The trailing ""
stops the Angular expression being evaluated to any text.
Then you can simply call {{myVariable}}
to output your variable value.
I found this very useful when iterating multiple nested arrays and I wanted to keep my current iteration info in one variable instead of querying it multiple times.
ngInit
can help to initialize variables.
<div ng-app='app'> <div ng-controller="MyController" ng-init="myVar='test'"> {{myVar}} </div> </div>
jsfiddle example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With