问题
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