Reputation: 89
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.
Upvotes: 0
Views: 193
Reputation: 4766
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/
Upvotes: 4