0

Learning the AngularJS. Trying to change an example from tutorial. Need ng-init value be equals to the value transmitted from script function. How it can be done? Code is below:

<html>
    <body>
        <h2>AngularJS Sample Application</h2>
        <div ng-app="mainApp"  ng-controller="clickController">
            <p>Total click: {{  click.clickCounter() }}</p>
            <button ng-click="count = count+1" 
              ng-init="count=click.clickCounter()">Click Me!</button>
        </div>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
        </script>
    </body>

    <script>
        var mainApp = angular.module("mainApp", []);

        mainApp.controller('clickController', function($scope) {
            $scope.click = {
                count: 15,
                clickCounter: function() {
                    var foo;
                    foo = $scope.click;
                    return foo.count;
                }
            };
        });
    </script>
</html>

Problem is with transfering the value of click.clickCounter() to ng-click.

1
  • what this code should do? Commented Sep 9, 2015 at 13:32

1 Answer 1

4

You issue is your are creating a new count variable on the root of your scope.

Your count vaiable if $scope.click.count however the ng-init ang ng-click are creating and updating $scope.count.

this fixes the issue

<button ng-click = "click.count = click.count+1" ng-init="click.count=click.clickCounter()">Click Me!</button>

EDIT: If you add {{count}} inside your app you will see the scope variable it is creating. One of the double edged swords of Angular is if you define variables in your view that don't exist on your scope Angular will create and add them to the scope for you.

EDIT 2: Your ng-init is obsolete. Seeing as you already created a count property of your $scope.click object it is already initialized and has a value.

Also see fiddle: http://jsfiddle.net/yjwskkat/

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

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.