0

Here is my html code

<div ng-app='app'>
<div ng-controller="MyController" ng-init="myVar=7">
    {{myVar}}
    <span ng-init="myVar=myVar+5">{{myVar}},</span>
    <span ng-init="myVar=myVar+15">{{myVar}},</span>
    <span ng-init="myVar=myVar+37">{{myVar}},</span>
</div>   

and script

var app = angular.module('app',[]);
app.controller('MyController', function() {});

The output I'm getting is 64,64,64,64

but I want output as 7,12,27,64

I'm trying to find things like ng-repeat but I cant kept these in an array

3
  • I have little understanding and I know angular.js doesn't work how I'm thinking, but there should be other ways to achieve this. I need those ways.. Commented Oct 24, 2013 at 11:06
  • WHy can you not do {{myVar+5}}, inside the span instead of using ng-init. Commented Oct 24, 2013 at 11:07
  • Dear Chandermani, I want to update the variable then and their itself. Commented Oct 28, 2013 at 5:59

1 Answer 1

1

In every ng-init you're altering the value of myVar that is data bound to all other instances; and that's why they all show the same. So rather do:

<div ng-app='app'>
<div ng-controller="MyController" ng-init="myVar=7">
    {{myVar}}
    <span>{{myVar+5}},</span>
    <span>{{myVar+15}},</span>
    <span>{{myVar+37}},</span>
</div>   
Sign up to request clarification or add additional context in comments.

3 Comments

Ohh my god.. yes.. I tried this in the begining itself, but not worked. Now it is working.. thanks alot
is there any way to re-assign the myVar variable like.. {{myVar}} {{myVar+=5}} {{myVar+=7}}
Just to be clear, it's important to know the workflow of AngularJS (docs.angularjs.org/guide/concepts) and realize that EVERY ng-init will run prior to any interpolation.

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.