我在理解如何使用控制器在页面上显示/隐藏元素时遇到问题。
有一个带有示例的代码 - 您可以通过单击"关闭编辑"来检查它。按钮(没有任何反应):
var appModule = angular.module('appModule', []);
appModule.controller('appCtrl', ['$scope',
function($scope) {
$scope.items = [1, 2, 3, 4, 5]
$scope.closeEdit = function(index, newValue) {
$scope.isEditing = false; // here I would like to close editing option but it doesn't work
//$scope.items[index] = newValue; // in next step I would like to update "item" value with new one but it doesn't work correctly
};
}
]);

table td:first-child,
input {
width: 100px;
}
table td {
border: 1px solid silver;
padding: 5px;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<table ng-controller="appCtrl">
<tr ng-repeat="item in items">
<td>
<div>
<span ng-hide="isEditing"> <!-- should hide when editing and update after it with new value -->
{{item}}
</span>
<input ng-show="isEditing" type="text" ng-model="newValue" placeholder="{{item}}" />
<!-- should show when editing -->
</div>
</td>
<td>
<button ng-hide="isEditing" ng-click="isEditing = !isEditing">OPEN EDIT</button>
<!-- should hide when editing -->
<button ng-show="isEditing" ng-click="closeEdit($index, newValue)">close edit</button>
<!-- should show when editing -->
</td>
</tr>
</table>
&#13;
我想改变价值&#34; isEditing&#34;通过控制器。通过像
这样的HTML来做这件事是没有问题的ng-click="isEditing = !isEditing"
但是下面的代码在控制器中无法正常工作:
$scope.isEditing = false;
它的目的是显示/隐藏按钮/字段以提供新值。
之后可能会有更新新值的问题。
如果你能解释 - 非常感谢。
答案 0 :(得分:1)
这是因为ng-repeat
创建了新的子范围,而您正在更改该范围内的isEditing
变量。要修复它,请在赋值中指定控制器:
ng-click="appCtrl.isEditing = !appCtrl.isEditing"
这是jsFiddle