jQuery or jqlite not working with elements inside <ng-view></ng-view>

感情迁移 提交于 2019-12-11 23:14:08

问题


index.html:

<div>
<p class="aaa">ppp</p>
<ng-view>

</ng-view>
</div>

general.html

<p class="bbb">pppppp</p>

javascript

var app = angular.module('StarterApp', ['ngMaterial','ngRoute','ngImgCrop']);

app.config(function($routeProvider){
        $routeProvider
            .when('/general',
                {
                    templateUrl:'../view/general.html'
                })
});

$(document).ready(function() {
    $(".aaa").on("click",function(){
         alert('clicked');
    });
    $(".bbb").on("click",function(){
         alert('clicked');
    });
});

It works for the element with class="aaa" but doesn't work for the elements inside the

 <ng-view></ng-view>

The jQuery code is outside of controller.


回答1:


document ready in jquery can happen before angular has finished loading (e.g. before it injects the ng-view). This is even more true if you use an on demand script system like require.js.

As such you should

A: Use Angular's version of document ready,

angular.element(document).ready(function () {
    $("#aaa").on("click",function(){
     alert('clicked');
    });
    $("#bbb").on("click",function(){
         alert('clicked');
    });
});

B: (The angular way)

Build an angular directive for any custom elements you want, or a form, or a widget, or w/e you are building (compartmentilize it) so that you can handle the directives link or compile function, where you can then subscribe to events on the element (like an anchor) and have access to it's event objects.



来源:https://stackoverflow.com/questions/32900475/jquery-or-jqlite-not-working-with-elements-inside-ng-view-ng-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!