是否有角度从模板中获取绑定?
换句话说,如果我有这样的话:
<div ng-repeat="item in list">
<div>{{item.name}}</div>
<div>{{item.state}}</div>
</div>
是否可以通过点击来更改项目的状态,因为重复的div会“记住”它是从哪个项目构建的?
答案 0 :(得分:4)
是的,您可以使用ng-click
指令触发当前范围的方法:
// In your view's controller:
function MyCtrl($scope, MyList) {
// You probably have something like that already to
// populate your list, using a $resource or $http GET call.
// Here I use a $resource which would be defined on your module.
$scope.list = MyList.query()
$scope.setState = function(state) {
// "this" refers to the current scope
this.item.state = state
}
}
// And in your view:
<div ng-repeat="item in list">
<div>{{item.name}}</div>
<div ng-click="setState('whatever')">{{item.state}}</div>
</div>
或者您可以直接在div上设置ng-click="item.state='whatever'"
这样的表达式,虽然这不太可测试 - 仅在端到端测试中 - 而且不太灵活,比如说要引入验证或其他东西)
HTH