【问题标题】:AngularJS string is not a functionAngularJS 字符串不是函数
【发布时间】:2014-05-18 05:40:12
【问题描述】:

为了缩短帖子,这是我的问题所需的所有信息,所以我制作了一个按钮,在点击时提供 +1 评级和 -1 评级的按钮,这是它的 HTML 代码,

<p>
<strong>Rating: </strong> {{ album.rating }}
<button class="btn btn-small" ng-click="upVoteRating(album)">+</button>
<button class="btn btn-small" ng-click="downVoteRating(album)">-</button>
</p>

没什么不寻常的,这里是使用范围和按钮功能的 angularjs 代码。

$scope. upVoteRating = 'upVoteRating';
$scope. downVoteRating = 'downVoteRating';

function upVoteRating(album) {

album.rating++;

}

function downVoteRating(album) {

if (album.rating > 0)
album.rating--;

}

所以根据我的猜测,代码没有问题,但是每次我点击页面上的按钮时,它都会在控制台上显示:

"TypeError: string is not a function
at http://localhost:1234/lib/angular/angular.min.js:168:37
at http://localhost:1234/lib/angular/angular.min.js:186:167
at g.$eval (http://localhost:1234/lib/angular/angular.min.js:104:308)
at g.$apply (http://localhost:1234/lib/angular/angular.min.js:105:48)
at HTMLButtonElement.o.event.dispatch (http://localhost:1234/lib/jquery-2.1.0.min.js:3:6055)
at HTMLButtonElement.r.handle (http://localhost:1234/lib/jquery-2.1.0.min.js:3:2830) angular.js:9507"

我不知道如何解决这个问题,我一直在寻找一个小时,所以请,如果您需要更多代码来帮助您找出问题,请立即询问!

再次感谢!

【问题讨论】:

  • 问题正是调试器告诉你的。字符串不是函数。您不能将字符串放在期望函数的位置。试试$scope. upVoteRating = upVoteRating; - JavaScript 函数是一阶的,你可以这样传递它们。

标签: javascript jquery node.js angularjs


【解决方案1】:

您在此处将其设置为字符串:

$scope.upVoteRating = 'upVoteRating';

并尝试在此处将其作为函数调用

<button class="btn btn-small" ng-click="upVoteRating(album)">+</button>

删除控制器中的引号,你应该很好:

$scope.upVoteRating = upVoteRating;
$scope.downVoteRating = downVoteRating;

【讨论】:

  • 这听起来很对,而且,你可以完全跳过函数的命名,直接写$scope.upVoteRating = function(){...
  • 非常感谢,我想我应该多加注意!
  • @user3502346 想一想,因为您现在知道如何在未来解决(并预防)这个问题。
  • @user3502346 如果这个答案解决了您的问题 - 请consider accepting it
猜你喜欢
  • 2014-06-29
  • 2013-06-17
  • 2012-12-14
  • 2015-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 2014-09-16
相关资源
最近更新 更多