最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to apply an AngularJS directive to ajax content? - Stack Overflow

programmeradmin1浏览0评论

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

JSbin: /

HTML

<html ng-app="app">
  <head>
<script src=".min.js"></script>
<script src=".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>");
});

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

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

HTML

<html ng-app="app">
  <head>
<script src="http://ajax.googleapis./ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis./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>");
});
Share Improve this question edited Apr 5, 2020 at 2:11 Dan 63.2k18 gold badges111 silver badges119 bronze badges asked May 22, 2013 at 20:48 Mariz MeloMariz Melo 8501 gold badge12 silver badges18 bronze badges 1
  • What did you try so far? Can you provide some sample code? – tschiela Commented May 22, 2013 at 20:54
Add a ment  | 

2 Answers 2

Reset to default 3

The new DOM must be accessible to the angular app in order to be piled 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).

It would be best if you could load your extra content from within the angular framework. Check out ng-include.

If that can't be used to do what you need, you'll have to manually call the angular pile service on the element, to pile it and link it onto the scope yourself using $pile.

Compiling elements touches the DOM, and therefore should be done within a custom directive if possible.

发布评论

评论列表(0)

  1. 暂无评论