我使用简单的语法来显示,在ng-repeat中隐藏元素
<div ng-controller='MainController as vm'>
<ul>
<li ng-repeat="item in vm.items" ng-click="vm.showItem()">
{{item}}
<span ng-show="show">test</span>
</li>
</ul>
当我使用范围时,everythink工作正常
$scope.showItem = function(){
this.show=!this.show;
}
但是与控制器相同的代码不起作用
vm = this;
vm.showItem = function(){
this.show=!this.show;
}
如何在ng-repeat中访问当前项目的show属性?
答案 0 :(得分:1)
从html中获取当前的this
实例
<li ng-repeat="item in vm.items" ng-click="vm.showItem(this)">
并在你的控制器中使用它
vm.showItem = function(_this){
_this.show=!_this.show;
}
您遇到的问题是this
上下文
更新了plunker http://plnkr.co/edit/pkxI68sGMXonDOA49EUq?p=preview
答案 1 :(得分:1)
var app = angular.module('myApp', []);
app.controller('MainController', function() {
vm = this;
vm.items = [];
for (var i = 0; i < 10; i++) vm.items.push({
value: i,
show: false,
showItem: function() {
this.show = !this.show
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MainController as vm">
<ul>
<li ng-repeat="item in vm.items" ng-click="item.showItem()">
{{item.value}}
<span ng-show="item.show">test</span>
</li>
</ul>
</div>
</div>
我们要通过将showItem
方法提取到Item
原型
var app = angular.module('myApp', []);
app.controller('MainController', function() {
vm = this;
vm.items = [];
for (var i = 0; i < 10; i++) vm.items.push(new Item(i));
function Item(value) {
this.value = value
this.show = false
}
Item.prototype.showItem = function() {
this.show = !this.show
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MainController as vm">
<ul>
<li ng-repeat="item in vm.items" ng-click="item.showItem()">
{{item.value}}
<span ng-show="item.show">test</span>
</li>
</ul>
</div>
</div>
下一步将Item
提取到角度工厂
答案 2 :(得分:0)
您需要使用vm.show = !vm.show;
vm = this;
vm.showItem = function(){
vm.show=!vm.show;
}
答案 3 :(得分:0)
用。
替换功能定义vm.show = !vm.show;
我附上了示例代码段。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script data-require="angular.js@1.5.5" data-semver="1.5.5" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script>
var app = angular.module('myApp', []);
app.controller('MainController', function () {
vm = this;
vm.items = [];
vm.start = 0;
vm.end = 20;
for (var i = 0; i < 10; i++) vm.items.push(i);
// return vm;
vm = this;
vm.show = true;
vm.showItem = function () {
vm.show = !vm.show;
}
});
</script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller='MainController as vm'>
<ul>
<li ng-repeat="item in vm.items" ng-click="vm.showItem()">
{{item}}
<span ng-show="vm.show">test</span>
</li>
</ul>
</div>
</div>
</body>
</html>