0

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.

Yellove
  • 165
  • 1
  • 2
  • 8

1 Answers1

0

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.

Ryan Mann
  • 5,178
  • 32
  • 42
  • Actually, now days I don't even use angular controllers, I make directives for everything and use bindToController so I don't have to use the $scope object ever getting rid of $scope inheritance issues. http://teropa.info/blog/2014/10/24/how-ive-improved-my-angular-apps-by-banning-ng-controller.html The really cool thing about bindToController and directives is you can make your directive controller global, or instanced.. Meaning you can design a directive that uses the same instance of it's controller, or creates new instances. – Ryan Mann Oct 02 '15 at 04:31
  • I changed $(document) to angular.element(document) but it still doesn't work. – Yellove Oct 02 '15 at 04:52