【问题标题】:How to apply an AngularJS directive to ajax content?如何将 AngularJS 指令应用于 ajax 内容?
【发布时间】:2013-05-18 01:39:56
【问题描述】:

我知道我可以apply 到模板/模板URL,但目前内容将从我的应用程序的另一个位置加载。

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代码:

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>");
});

【问题讨论】:

  • 到目前为止你尝试了什么?能否提供一些示例代码?

标签: javascript html angularjs angularjs-directive


【解决方案1】:

新的 DOM 必须可供 Angular 应用访问才能正确编译。这是执行此操作的一种方法(不是唯一方法)。要将新的 DOM 应用到应用程序的 $rootScope,请更改以下内容:

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

到:

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

根据Angular docs

$apply() 用于从 Angular 框架外部执行 Angular 表达式。 (例如来自浏览器 DOM 事件、setTimeout、XHR 或第三方库)。

【讨论】:

  • 谢谢 sh0ber。我发现你也可以像这样使用 $compile...: $compile($("body").append("
    here too
    "))($scope);
  • app.run() 的上下文中使用 $apply 和 $compile 有什么区别?谢谢
【解决方案2】:

如果您可以从 Angular 框架中加载额外的内容,那将是最好的。查看ng-include

如果这不能用来做你需要的事情,你必须手动调用元素上的角度编译服务,编译它并使用$compile自己将它链接到范围。

编译元素会触及 DOM,因此如果可能的话,应该在自定义指令中完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2015-07-30
    相关资源
    最近更新 更多