Runtime Terror
Runtime Terror

Reputation: 6742

How to store variable in an AngularJS HTML template?

How can I store values to variable for example on click in angular? I have the following code which doesn't save the value into variable:

HTML:

<div ng-app='app'>
    <a ng-controller="MyController" href="#" ng-click="variable = 1">

    </a>
    {{variable}}
</div>

Controller:

var app = angular.module('app',[]);

app.controller('MyController', function($scope)
{
});

jsfiddle code

Upvotes: 2

Views: 4723

Answers (4)

kasimoglou
kasimoglou

Reputation: 384

Your variable binding {{variable}} should be inside controller's scope. So move ng-controller to an element that will contain variable binding.

Upvotes: 5

Mark Ni
Mark Ni

Reputation: 2401

Your syntax is correct, what went wrong is you put your controller declaration in the wrong place.

You just need move it to the outer layer, no need for ng-init or function (but might be a better practice):

<div ng-app='app' ng-controller="MyController">
    <a  href="#" ng-click="variable=1">
    click me!
    </a>
    {{variable}}
</div>

http://jsfiddle.net/ybavzec4/3/

Upvotes: 2

Janus Troelsen
Janus Troelsen

Reputation: 21290

You need to initialize the variable. See http://plnkr.co/edit/dmSNVJ3BGIeaWaddKtZe

<body ng-app="">
  <button ng-click="count = 1" ng-init="count='not set'">
  Increment
</button>
<span>
  count: {{count}}
</span>
</body>

Upvotes: 3

H&#229;kan Fahlstedt
H&#229;kan Fahlstedt

Reputation: 2095

Use a function to set the variable:

HTML:

<div ng-app='app'>
    <a ng-controller="MyController" href="#" ng-click="setVariable()">

    </a>
    {{variable}}
</div>

Controller:

var app = angular.module('app',[]);

app.controller('MyController', function($scope)
{
    $scope.setVariable = function() {
        $scope.variable = 1;
    }
});

Upvotes: 2

Related Questions