Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set angular scope variable in markup

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/

like image 278
Nix Avatar asked May 28 '13 15:05

Nix


2 Answers

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.

like image 170
Glogo Avatar answered Sep 25 '22 12:09

Glogo


ngInit can help to initialize variables.

<div ng-app='app'>     <div ng-controller="MyController" ng-init="myVar='test'">         {{myVar}}     </div> </div> 

jsfiddle example

like image 38
Mark Coleman Avatar answered Sep 22 '22 12:09

Mark Coleman