2

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

0

4 Answers 4

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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>

Comments

2

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;
    }
});

1 Comment

Note that variable binding is out of controller's scope.
2

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.