Open Wscats opened 8 years ago
下面的代码会根据你点击的数字变成红色,这里我们在ng-repeat渲染完成后绑定事件,注意一定是要DOM完全渲染后再去绑定,不然事件会绑定失败 重点就是加上在组件中加上这个DOM的完全渲染完成的判断
if (scope.$last) { // 这个判断意味着最后一个元素渲染完成 //scope.$eval(attr.chooseItem) // 执行绑定的表达式 }
全部代码
<!DOCTYPE html> <html ng-app="wsscat"> <head> <meta charset="UTF-8"> <title></title> <script src="../js/angular.js"></script> <!--<script src="zepto_1.1.3.js"></script>--> </head> <body ng-controller="indexCtrl"> {{name}} <ul> <li choose-item ng-repeat="item in items">{{item}}</li> </ul> </body> <script> var app = angular.module('wsscat', []); app.controller('indexCtrl', function($scope) { $scope.name = "wsscat" $scope.items = ['1', '2', '3', '4', '5'] }) app.directive('chooseItem', function() { return { link: function(scope, ele, attr) { if(scope.$last) { scope.$eval(function() { //如果引入jquery和zepto时候的写法 //$('li').bind('click', function() { //$(this).toggleClass('choosed') //console.log('toggleClass') //}) console.log(ele) angular.element(document.querySelectorAll('li')).bind('click', function() { angular.element(this).toggleClass('choosed') }) }()) } } } }) </script> <style> .choosed { color: red; } </style> </html>
在ng-repeat中我们可以再嵌套一个ng-repeat 外层格式为ng-repeat="links in slides" 内层格式为ng-repeat="link in links track by $index" 注意要加上track by和索引值$index
ng-repeat="links in slides"
ng-repeat="link in links track by $index"
<!DOCTYPE html> <html ng-app="wsscat"> <head> <meta charset="UTF-8"> <title></title> </head> <script src="../js/angular.js"></script> <body ng-controller="indexCtrl"> {{name}} <div ng-repeat="links in slides"> <hr/> <div ng-repeat="link in links track by $index"> {{link}} </div> </div> </body> <script> var app = angular.module('wsscat', []); app.controller('indexCtrl', function($scope) { $scope.name = "wsscat"; $scope.slides = [ [1, 1, 1], [4, 5, 6], ]; }) </script> </html>
ng-repeat绑定事件
下面的代码会根据你点击的数字变成红色,这里我们在ng-repeat渲染完成后绑定事件,注意一定是要DOM完全渲染后再去绑定,不然事件会绑定失败 重点就是加上在组件中加上这个DOM的完全渲染完成的判断
全部代码
ng-repeat嵌套
在ng-repeat中我们可以再嵌套一个ng-repeat 外层格式为
ng-repeat="links in slides"
内层格式为ng-repeat="link in links track by $index"
注意要加上track by和索引值$index