单击“ng-repeat”元素时无法对“ng-show”进行随机播放

时间:2015-08-10 05:39:46

标签: angularjs angular-directive

点击我正在显示列表的元素。以及点击相同的列表元素,我隐藏了列表。但是点击列表元素而不隐藏父级。

这是片段。单击该节目,然后单击列表元素之一。



var app = angular.module('dropdown', []);

app.controller('MainCtrl', function($scope) {
  $scope.show = false;
  $scope.names = ["one", "click and hide ", "three"]
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="dropdown" ng-controller="MainCtrl">
    <span ng-click="show = !show">Show me</span>
    <ul ng-show="show">
      <li ng-repeat="name in names" ng-click="show = !show">{{name}}</li> <!-- not hiding on click -->
    </ul>
  </div>
&#13;
&#13;
&#13;

这里有什么问题?如何解决?

3 个答案:

答案 0 :(得分:2)

ng-repeat创建了一个新的范围。您需要$parent.show = !$parent.show

var app = angular.module('dropdown', []);

app.controller('MainCtrl', function($scope) {
  $scope.show = false;
  $scope.names = ["one", "click and hide ", "three"]
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="dropdown" ng-controller="MainCtrl">
    <span ng-click="show = !show">Show me</span>
    <ul ng-show="show">
      <li ng-repeat="name in names" ng-click="$parent.show = !$parent.show;">{{name}}</li> <!-- not hiding on click -->
    </ul>
  </div>

答案 1 :(得分:1)

您可以声明为函数并从任何位置进行调用。所以你可以这样:

var app = angular.module('dropdown', []);

app.controller('MainCtrl', function($scope) {
  $scope.show = false;
  $scope.names = ["one", "click and hide ", "three"];
  $scope.toggle = function(){
      $scope.show = !$scope.show;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="dropdown" ng-controller="MainCtrl">
    <span ng-click="toggle()">Show me</span>
    <ul ng-show="show">
      <li ng-repeat="name in names" ng-click="toggle()">{{name}}</li> <!-- Now this is hiding on click -->
    </ul>
  </div>

答案 2 :(得分:0)

<div ng-app="dropdown" ng-controller="MainCtrl">
<span ng-click="show = !show">Show me</span>
<ul ng-show="show">
  <li ng-repeat="name in names" ng-click="$parent.show = !$parent.show">{{name}}</li> <!-- not hiding on click -->
</ul>

这有用吗?你必须打电话给父母的范围:)