AngularJS - $index, $event, $log
原文: https://thinkster.io/egghead/index-event-log
--------------------------------------------------------------
$index is a way to show which iteration of a loop you’re in. If we set up an ng-repeat to repeat over the letters in ‘somewords’, like so:
<div ng-app="app">
<div ng-repeat="item in 'somewords'.split('')">
{{$index + 1}}. {{item}}
</div>
</div>
We can see that we get a listing of all the characters in ‘somewords’ with the index next to it.
Now, let’s add an ng-click attribute to the div as “ev = $event” and a binding to ev.pageX. Let’s also set this div’s class to “button” since we’re going to be clicking on it
<div ng-app="app">
<div
class="button"
ng-repeat="item in 'somewords'.split('')"
ng-click="ev = $event"
>
{{$index + 1}}. {{item}}
{{ev.pageX}}
</div>
</div>
Now we can click on all of these buttons and whenever we click we get the extra number next to our index and character. This is the x value of where we’re clicking, and this shows that we can access the event that’s happening through $event.
If we want to log this event, we can do so by using $log. In order to use $log without setting up a controller, we can put it on the root scope of our application. We need to set up the run phase of our application and inject $rootScope and $log in order to expose $log to $rootScope
var app = angular.module("app", []);
app.run(function($rootScope, $log){
$rootScope.$log = $log;
});
Now we’re able to access the $log function anywhere within our app. (Note that you rarely want to put anything on the $rootScope as anything on the $rootScope will be available throughout the app.) Let’s change the ng-click attribute to “$log.debug($event)”
<div ng-app="app">
<div
class="button"
ng-repeat="item in 'somewords'.split('')"
ng-click="$log.debug($event)"
>
{{$index + 1}}. {{item}}
{{ev.pageX}}
</div>
</div>
Now we can open up our console and click on any of the buttons and we’ll see that the MouseEvent is being logged to the console. You can turn off the debug level of the logger in the config phase of the app by using $logProvider and calling debugEnabled and passing it false.
var app = angular.module("app", []);
app.config(function($logProvider){
$logProvider.debugEnabled(false);
});
app.run(function($rootScope, $log){
$rootScope.$log = $log;
});
Be sure to use proper logging levels in order for debugEnabled to work, as any info or warnings will still be logged
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现