添加" ng-class"在所选元素的父母身上

时间:2016-04-27 10:41:26

标签: javascript angularjs

所以与ng-class相关的另一个问题是......

点击<ul>

中的<button>点击,向<li>添加课程

demo

HTML:

<div ng-app="myApp">
<section ng-controller="myCtrl">
    <ul>
        <li ng-repeat="item in model.items" class="commonClass">{{ item.name }}</li>
        <li><button>
        active
        </button></li>
    </ul>
    <ul>
        <li ng-repeat="item in model.items" class="commonClass">{{ item.name }}</li>
        <li><button>
        active
        </button></li>
    </ul>
</section>
</div>

JS:

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

app.controller('myCtrl', function ($scope) {

    $scope.model = {
        selected: null,
        items : [
            {name: "Apple"}, 
            {name: "Banana"}, 
            {name: "California"}
         ]
    };
})

1 个答案:

答案 0 :(得分:1)

试试这个

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

app.controller('myCtrl', function($scope) {

  $scope.uls = [{model: { selected: null, items: [{ name: "Apple" }, { name: "Banana" }, { name: "California" }] }}, {model:{ selected: null, items: [{ name: "Apple" }, { name: "Banana" }, { name: "California" }] }}];

  /* $scope.model = {
    selected: null,
    items: [{
      name: "Apple"
    }, {
      name: "Banana"
    }, {
      name: "California"
    }]
  }; */
})
.on {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <section ng-controller="myCtrl">
    <ul ng-class="{'on': ul.onIsOn}" ng-repeat="ul in uls">
      <li ng-repeat="item in ul.model.items" class="commonClass">{{ item.name }}</li>
      <li>
        <button ng-click="ul.onIsOn = !ul.onIsOn">
          active
        </button>
      </li>
    </ul>
  </section>
</div>