JS编译HTML指令后装 [英] Compile JS Directive after HTML loaded

查看:87
本文介绍了JS编译HTML指令后装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想在HTML加载后编译指令。

So I'm wanting to compile a directive after the HTML is loaded.

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

gifApp.directive('addition', function() {
  return function(scope, element) {
    element.html("<h1>" + scope.gif.name + "</h1>")

  }
});

function MainCtrl ($scope) {
  $scope.gif = {name: "Cat jumps on car"}

  $scope.push_code = function() {
    $("body").html("<div addition></div>")
  }
}

每当功能 push_ code 被称为GIF名称在屏幕上不显示。它是不可能编译code完成窗口后,用一条指令加载?如果可能的话,我怎么解决这个问题?

Whenever the function push_code is called the gif name is not displayed on the screen. Is it not possible to compile the code after the window is done loading with a directive? If it is possible, how do I fix this?

推荐答案

窗口加载之后,但角度需要知道,当你做你可以添加HTML。现在,因为你加入 DIV 使用jQuery角不知道DOM发生了变化。因而它没有得到一个机会,你的指令适用于您的新元素。

You can add HTML after the window has loaded but Angular needs to know when you do. Right now since you're adding the div using jQuery Angular doesn't know the DOM has changed. And thus it doesn't get a chance to apply your directive to your new element.

我建议解决这一问题是采用了棱角分明的内置的jQuery的版本称为 jQlite方式

The way I'd recommend dealing with this is using Angular's built-in version of jQuery called jQlite.

下面是一个使用的 push_ code()版本=nofollow的> jQlite

Here's a version of push_code() using jQlite:

push_code = function() {
   compiled = $compile('<div addition></div>')($scope);
   angular.element(document).find('body').append(compiled)
}

下面我们创建了一个角的DOM元素,并告诉角至$编译它在当前范围(这将适用于你的指令)。然后我们加入角元素添加到在jQlite相当于你的jQuery的方法。

Here we create an Angular DOM element and tell Angular to $compile it on the current scope (which will apply your directive). Then we add that Angular element to the body in the jQlite equivalent of your jQuery approach.

下面是一个演示: http://jsfiddle.net/Me2HW/3/

我把 push_ code() $超时内通话只是为了演示有没有时间依赖性这里。您可以拨打这个电话,只要你愿意,包括窗口已加载好后,和它的作品。

I put the push_code() call inside $timeout just to demonstrate there's no timing dependency here. You can make this call whenever you'd like, including well after the window has loaded, and it works.

这篇关于JS编译HTML指令后装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆