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/


Solution 1:

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.

Solution 2:

ngInit can help to initialize variables.

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

jsfiddle example

Solution 3:

Create a directive called myVar with

scope : { myVar: '@' }

and call it like this:

<div name="my_map" my-var="Richmond,VA">

Note in particular the camel case reference in the directive to the hyphenated tag name.

For more information see "Understanding Transclusion and Scopes" here:- http://docs.angularjs.org/guide/directive

Here's a Fiddle that shows how you can copy values from attributes to scope variables in various different ways within a directive.

Solution 4:

You can set values from html like this. I don't think there is a direct solution from angular yet.

 <div style="visibility: hidden;">{{activeTitle='home'}}</div>

Solution 5:

You can use ng-init as shown below

<div class="TotalForm">
  <label>B/W Print Total</label>
  <div ng-init="{{BWCount=(oMachineAccounts|sumByKey:'BWCOUNT')}}">{{BWCount}}</div>
</div>
<div class="TotalForm">
  <label>Color Print Total</label>
  <div ng-init="{{ColorCount=(oMachineAccounts|sumByKey:'COLORCOUNT')}}">{{ColorCount}}</div>
</div>

and then use the local scope variable in other sections:

<div>Total: BW: {{BWCount}}</div>
<div>Total: COLOR: {{ColorCount}}</div>