gpt4 book ai didi

javascript - ng-click 在 ng-repeat 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 11:14:11 24 4
gpt4 key购买 nike

我有一个为用户显示卡片的指令。每张卡片都有一个“aww”或“naww”按钮。 AngularJS 遍历 ng-repeat 并生成每张卡片。当用户单击该按钮时,我希望该特定卡片的“aww”或“naww”值增加。不幸的是,当我现在点击按钮时,没有任何反应,值仍然为零。如何让每张卡片的 aww 和 naww 值递增?

view1.html

<div class="container">
<div ng-repeat="animal in animals" my-animal="animal"></div>
</div>

view1.js

'use strict';

angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])

.controller('View1Ctrl', ['$scope',function($scope) {

$scope.animals = [{'name':'Perry','animal':'Bird','awws':0,'nawws':0,
'image-url': 'https://goo.gl/Vtcvk5'},
{'name':'Max','animal':'Cat','awws':0,'nawws':0,
'image-url':'https://goo.gl/bqOQci'
},
{'name': 'Julian','animal':'Duck','awws':0,'nawws':0,
'image-url':'https://goo.gl/v9GyTz'
}];
$scope.add = function(item){
item = item + 1;
};
}])

.directive('myAnimal', function() {
return {
scope: {
item: '=myAnimal'
},
restrict: 'EA',
templateUrl: 'view1/card-template.html'
};
});

cardtemplate.html

<div class="card">
<img class="card-img-top img-responsive" ng-src="{{item.image-url}}" alt="Cute animal">
<div class="card-block">
<h4 class="card-title">{{item.name}}</h4>
<p class="card-text">{{item.animal}}</p>
<button type="button" ng-click="add(item.awws)" class="btn btn-success">Aww +1 </button>
{{item.awws}}
<button type="button" ng-click="add(item.nawws)" class="btn btn-danger">Naww -1 </button>
{{item.nawws}}
</div>
</div>

最佳答案

发生这种情况是因为您的 Controller 的“$scope.add”函数不在您的 myAnimal 指令(具有隔离范围)的范围内。

此外,您以错误的方式使用了该指令。 my-animal 是您的指令,而不是指令的属性。首先,将调用 template 的指令更改为:

<div class="container">
<div ng-repeat="animal in animals" my-animal animal="animal" add="add"></div>
</div>

指令:

.directive('myAnimal', function() {
return {
scope: {
item: '=animal',
add: '&' //method binding here
},
restrict: 'EA',
templateUrl: 'view1/card-template.html'
};
});

如您所见,我添加了另一个属性,它将 Controller 中的“add”函数绑定(bind)到指令,从而使其在指令范围内可用。 & 用于实现此目的。

关于javascript - ng-click 在 ng-repeat 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33369025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com