angular.js - Why binding events to Angular directives does not take effect
过去多啦不再A梦
过去多啦不再A梦 2017-05-15 17:03:39
0
5
503

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?

过去多啦不再A梦
过去多啦不再A梦

reply all(5)
给我你的怀抱

This has nothing to do with scope, it is purely a typical jquery => angularwrong expression.

AngularJS的指令,作为一种“声明式”的API,玩法和jqueryThe "imperative" API is very different, and it's easy to make mistakes when you mix them.

  1. Basic common sense errors, id是用来表示元素唯一性的,可你用在了ng-repeat上,也就是说可能出现若干个元素的id都是need-another-js,这和jqueryangular都没关系,纯粹是htmllack of knowledge

  2. ng-repeat作为angular提供的指令,需要经过angularcompilelinking过程,导致,当你的$('#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:

<p ng-repeat="item in list" class="need-another-js"></p>

No needidclass

<script>
    $(document).on('click', '.need-another-js', function(){
        // do something
    });
</script>

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

黄舟
<p ng-repeat="item in list" id="need-another-js"></p>
<!--ng-repeat生成了一系列id为need-another-js的DOM元素,而DOM元素的ID是不能重复的-->
<script>
    $('#need-another-js').click(function(){//可能在ng-repeat还未执行完成的时候便执行了
    //需在ng-repeat执行完成时,设置onclick事件才有效
        // do something
    })
</script>
大家讲道理

angular has a binding event it supports ng-click

You can try writing it like this

<p ng-repeat="item in list" ng-click="click()"></p>
<script>
    //省略其他控制器的写法
    $scope.click = function() {
       //do something
   }
</script>
洪涛

When I was learning Angular, I switched directly from jq to angular. Angular can do everything jq can do

过去多啦不再A梦

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template