Click here to Skip to main content
15,894,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am learning Angular. Please tell me why the $watch at the very bottom does not work:

HTML
<html>
<head>
	<link rel="Stylesheet" href="c.css" type="text/css" />
</head>
<body ng-app ng-controller='StudentListController'>
	<ul >
		<li ng-repeat='student in students'>
			<a href='/student/view/{{student.id}}' class="menu-{{student.valid}}">{{student.name}}</a>
			<input type="text" ng-model="student.quantity" />
		</li>
	</ul>
	<button ng-click="Sum()" class="menu-true">Sum</button>
	<div>{{sum}}</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<script>
	var students = [{ name: 'Mary Contrary', id: '1', valid: 'true', quantity: 0 },
{ name: 'Jack Sprat', id: '2', valid: 'false', quantity: 0 },
{ name: 'Jill Hill', id: '3', valid: 'false', quantity: 0 }];

	function StudentListController($scope)
	{
		$scope.students = students;
		$scope.sum = 0;

		$scope.Sum = function ()
		{
			$scope.sum = 0;
			for (var i = 0;  i < $scope.students.length; i++)
			{
				$scope.sum = parseFloat($scope.sum) + parseFloat($scope.students[i].quantity);
			}
		};

		$scope.$watch($scope.students[1], $scope.Sum, 'true');
	}

</script>
</html>
Posted
Comments
Richard MacCutchan 3-Apr-14 4:25am    
What do you mean by "does not work"?

1 solution

You can use this alternative code

XML
<html>
<body ng-app ng-controller='StudentListController'>
    <ul>
        <li ng-repeat='student in students'><a href='/student/view/{{student.id}}' class="menu-{{student.valid}}">
            {{student.name}} </a>
            <input ng-model="student.quantity" ng-change='Sum()' />
        </li>
    </ul>
    <button ng-click="Sum()" class="menu-true">
        Sum</button>
    <div>
        {{sum}}</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<script type="text/javascript">
    var students = [{ name: 'Mary Contrary', id: '1', valid: 'true', quantity: 0 },
{ name: 'Jack Sprat', id: '2', valid: 'false', quantity: 0 },
{ name: 'Jill Hill', id: '3', valid: 'false', quantity: 0}];

    function StudentListController($scope) {
        $scope.students = students;
        $scope.sum = 0;

        $scope.Sum = function () {
            $scope.sum = 0;
            for (var i = 0; i < $scope.students.length; i++) {
                $scope.sum = parseFloat($scope.sum) + parseFloat($scope.students[i].quantity);
            }
        };

    }

</script>
</html>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900