Akash Singh
Akash Singh

Reputation: 67

What to use for calling function attached to $scope

Controller has following function:

$scope.incrementLikes = function (technology) {
   technology.likes++;
}

Now what should I use to call this function while calling it like in the following case:

<input type="button" value="Like" ng-click="{{incrementLikes(technology)}}" />

Should I use {{incrementLikes(technology)}} or incrementLikes(technology), we use {{variable_name}} if a "variable_name" is added to $scope, should we do the same for function calls or different, and why?

technology is an object of technologies:

techologies = [
  { name: "C#", likes: 0, dislikes: 0 },
  { name: "ASP.NET", likes: 0, dislikes: 0 },
  { name: "SQL", likes: 0, dislikes: 0 },
  { name: "AngularJS", likes: 0, dislikes: 0 },
]

Upvotes: 0

Views: 37

Answers (1)

Aleksey Solovey
Aleksey Solovey

Reputation: 4191

General rule is that you don't need {{...}} if it has ng-. So the syntax would be: incrementLikes(technology). As long as technology is scoped, it will update likes correctly. Here is a demo:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">

    <div ng-repeat="technology in techologies">
      <input type="button" value="Like" ng-click="incrementLikes(technology)" /> {{technology}}
      <input type="button" value="Dislike" ng-click="decrementLikes(technology)" />
    </div>

  </div>

  <script>
    var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope) {
      $scope.techologies = [{
          name: "C#",
          likes: 0,
          dislikes: 0
        },
        {
          name: "ASP.NET",
          likes: 0,
          dislikes: 0
        },
        {
          name: "SQL",
          likes: 0,
          dislikes: 0
        },
        {
          name: "AngularJS",
          likes: 0,
          dislikes: 0
        },
      ];

      $scope.incrementLikes = function(technology) {
        technology.likes++;
      }
      $scope.decrementLikes = function(technology) {
        technology. dislikes++;
      }
    });
  </script>

</body>

</html>

Upvotes: 1

Related Questions