Because I have just come into contact with Angular, some concepts are still very vague. I tried to find the answer to this question through Google, but did not find a suitable answer, so I would like to ask you here. Here is a rough code:
<p ng-repeat="item in list" class="need-another-js"></p>
<script>
$('.need-another-js').click(function(){
// do something
})
</script>
If ng-repeat
is removed, the effect of JS code can be achieved, but after adding ng-repeat
, the effect does not exist. Is this because of the Angular scope problem?
This has nothing to do with scope, it is purely a typical
jquery
=>angular
wrong expression.AngularJS
的指令,作为一种“声明式”的API,玩法和jquery
The "imperative" API is very different, and it's easy to make mistakes when you mix them.Basic common sense errors,
id
是用来表示元素唯一性的,可你用在了ng-repeat
上,也就是说可能出现若干个元素的id
都是need-another-js
,这和jquery
、angular
都没关系,纯粹是html
lack of knowledgeng-repeat
作为angular
提供的指令,需要经过angular
的compile
、linking
过程,导致,当你的$('#need-another-js').click
在为#need-another-js
元素注册事件的时候,这个元素其实还没有被angular
生成到DOM
, this is the key to not taking effect.Just for your example, you can make the following modifications to make it effective:
Although I don't recommend this way of writing, since you chose to mix "imperative" and
声明式
API, you must have your reasons.Added:
Regarding how
angular
works, I think for students who are just getting started, it is helpful to take a look at this introduction on the official website:Document address: concepts
angular has a binding event it supports ng-click
You can try writing it like this
When I was learning Angular, I switched directly from jq to angular. Angular can do everything jq can do
ng-repeat is to dynamically add DOM elements. If you use the click method to bind events to dynamically added elements, it will not be triggered. If you like to use jquery, use the method proposed by leftstick, but it is recommended to use the angular method proposed by mumofa