我在使用 Angular Controller 时遇到了一个奇怪的错误。此错误重现 JSFiddle HTML 示例:
<div ng-app>
<div ng-controller="GroupViewerController">
<table class="table table-striped">
<tr ng-repeat="a in arr" ng-controller="OneGroupViewerController">
<td >{{a}} <button ng-click="change(a)">change</button></td>
</tr>
</table>
</div>
<div ng-controller="oneGroupItemsController">
<input type="text" ng-model="$parent.selectedObject">
</div>
</div>
JavaScript:
function GroupViewerController($scope) {
$scope.selectedObject = "test";
$scope.arr = ["a","b"]
}
function OneGroupViewerController($scope) {
$scope.change = function (a){
$scope.$parent.selectedObject = a;
}
}
function oneGroupItemsController($scope) {
}
错误:
- 为什么已经引用了父 Controller 对象,但“test”没有出现在文本框中
- 按下按钮更改时,为什么文本框包含
selectedObject
的新值
最佳答案
你犯了一些小错误,同时使用 ng-controller 和 ng-repeat 也不是一个好主意。
HTML:
<div ng-app>
<div ng-controller="GroupViewerController">
<table class="table table-striped" >
<tr ng-repeat="a in arr" ng-controller="OneGroupViewerController">
<td >{{a}} <button ng-click="change(a)">change</button></td>
</tr>
</table>
<div ng-controller="oneGroupItemsController">
<input type="text" ng-model="$parent.updateVar.selectedObject">
</div>
</div>
</div>
JS:
function GroupViewerController($scope) {
$scope.updateVar = {};
$scope.updateVar.selectedObject = "test";
$scope.arr = ["a","b"]
}
function OneGroupViewerController($scope) {
$scope.change = function (a){
$scope.$parent.updateVar.selectedObject = a;
}
}
function oneGroupItemsController($scope) {
}
工作 fiddle :https://jsfiddle.net/3L4gg6jv/7/
关于javascript - 父子 Controller 的 Angular JS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39691545/