假设有一个 Controller 来操作示波器上的一些数据,那么向 Controller 提供该数据的最佳做法是什么?
例如,如果我有一个项目列表,我可能需要一个 ListController 来操作列表,并需要一个 ItemController 来操作单个项目。但是我如何给每个 ItemController 一个项目来使用呢?
在下面的例子中,doSomethingToItem 将如何访问项目。当嵌套在 ngRepeat 中时,项目是 $scope.item,但在选择 View 中,我们要操作的项目是 $scope.selection。
angular.module('MyApp', [])
.controller('ListController', function($scope, $http) {
$scope.list = $http.get(...);
$scope.selection = null;
})
.controller('ItemController', function($scope) {
$scope.doSomethingToItem = function() {
...
};
})
<div ng-controller="ListController">
<div ng-repeat="item in list" ng-click="selection = item">
<div ng-controller="ItemController">
<button ng-click="doSomethingToItem()">Do Something</button>
</div>
</div>
<div ng-show="selection"
<div ng-controller="ItemController">
<button ng-click="doSomethingToItem()">Do Something</button>
</div>
</div>
</div>
这不是常见的结构,还是我思维倒退了?
最佳答案
您应该明白,在您的情况下,Angular 会创建 n+1 个 ItemController。 N 用于项目,1 用于选择部分。
为了更轻松地传递需要处理的对象,您可以将方法签名更改为
doSomethingToItem(item)
在 html 中做
<button ng-click="doSomethingToItem(item)">Do Something</button>
在这两个地方。
否则对于重复情况 item
变量包含您可以在 ItemController 中访问的对象
selection
变量包含对选择 Controller 的引用,可以从选择部分下定义的 Controller 实例中引用。
更新:ng-repeat 和 selection 中的表达式会有所不同
<button ng-click="doSomethingToItem(item)">Do Something</button>
和
<div ng-show="selection"
<div ng-controller="ItemController">
<button ng-click="doSomethingToItem(selection)">Do Something</button>
</div>
</div>
关于javascript - 提供 AngularJS Controller 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20366359/