[英]ng-change not calling a function
我的ng表正在這樣構建
<table ng-table="storeCommandsTableParams" class="table tile">
<tr ng-repeat="storeCommand in $data">
<td>
<input type="checkbox" ng-change="vm.toggleCommandSelection(storeCommand)" ng-model="vm.selectedCommands" >
</td>
</tr>
</table>
而且我有這樣的控制器設置。
var vm = this;
vm.selectedCommands = { };
vm.toggleCommandSelection = function (storeCommand) {
var idx = vm.selectedCommands.indexOf(storeCommand);
// is currently selected
if (idx > -1) {
vm.selectedCommands.splice(idx, 1);
}
// is newly selected
else {
vm.selectedCommands.push(storeCommand);
}
};
我要完成的工作是,當用戶單擊復選框時,應將相應的storeCommand發送到vm.toggleCommandSelection函數,以便我可以選擇storeCommands列表。 但是不會觸發此功能。
您的模型不是storeCommand
而是vm.selectedCommands
。 因此,在這種情況下,單擊復選框不會觸發ng-change
。 也許您可以使用ng-click
代替。
嘗試這個
<input type="checkbox" ng-click="vm.toggleCommandSelection($event, storeCommand)">
var vm = this;
vm.selectedCommands = [];
vm.toggleCommandSelection = function ($event, storeCommand) {
var idx = vm.selectedCommands.indexOf(storeCommand);
if ($event.target.checked) {
if (idx === -1) {
vm.selectedCommands.push(storeCommand);
}
}
else {
if (idx > -1) {
vm.selectedCommands.splice(idx, 1);
}
}
};
問題尚未解決,但我建議您使用$ scope。 在這里,我假設您在控制器中的所有數據都是$ scope.data
從末尾的HTML中:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<table ng-table="storeCommandsTableParams" class="table tile">
<tr ng-repeat="category in categories">
<td>
<label class="checkbox" for="{{category.id}}">
<input type="checkbox" ng-model="selection.ids[category.id]" name="group" id="{{category.id}}" / >
{{category.name}}
</td>
</tr>
<pre ng-bind="selection.ids | json"></pre>
</table>
</body>
</html>
在相應控件的腳本中,輸入:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.categories = [ { "name": "Sport", "id": "50d5ad" } , {"name": "General", "id": "678ffr" } ];
$scope.selection = {
};
});
嗨,據我了解,我已經用虛擬數據更新了答案。 也請找工作鏈接plunker這里PLUNKER
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.