Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply an AngularJS directive to ajax content?

I know I can apply to the template/templateURL, but currently the content will load from another place in my application.

JSbin: http://jsbin.com/imuseb/1/

HTML

<html ng-app="app">
  <head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>

  </head>
  <body>

    <div alert>here</div>

  </body>
</html>

JS code:

var app = angular.module('app', []);

app.directive('alert', function (){
  return {
    link: function (scope, element, attrs) {
      element.on("click", function (){
        alert("here");
      });
    }
  };
});


$(function (){
   $("body").append("<div alert>here too</div>");
});
like image 289
Mariz Melo Avatar asked Oct 21 '22 09:10

Mariz Melo


1 Answers

The new DOM must be accessible to the angular app in order to be compiled correctly. Here is one way to do this (not the only way). For applying the new DOM to the app's $rootScope, change this:

$(function (){
    $("body").append("<div alert>here too</div>");
});

to:

app.run(function($rootScope){
    $rootScope.$apply($("body").append("<div editable>here too</div>"));
});

According to the Angular docs:

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

like image 145
Dan Avatar answered Oct 24 '22 04:10

Dan