用于调用附加到$ scope的函数的用途

时间:2018-02-05 11:02:58

标签: angularjs

控制器具有以下功能:

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

现在我应该在调用它时调用此函数,如下例所示:

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

我应该使用 {{incrementLikes(technology)}} 还是 incrementLikes(技术),如果&#34; variable_name&#34,我们会使用{{variable_name}} ;是否添加到$ 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 },
]

1 个答案:

答案 0 :(得分:1)

一般规则是,如果{{...}},则您不需要ng-。所以语法是:incrementLikes(technology)。只要technology具有范围,它就会正确更新喜欢的内容。这是一个演示:

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;