【发布时间】:2015-01-16 11:10:36
【问题描述】:
我有一个遗留应用程序,它通过 jQuery 将一些内容插入到 DOM 中。我希望代码库的遗留部分负责编译它插入到 DOM 中的 html。
我可以让它使用$compile 编译初始html,但是不会编译由指令的模板或templateUrl 添加的任何DOM 元素,除非我从指令本身中调用$scope.$apply()。
我在这里做错了什么?
小提琴链接:http://jsfiddle.net/f3dkp291/15/
index.html
<div ng-app="app">
<debug source='html'></debug>
<div id="target"></div>
</div>
application.js
angular.module('app', []).directive('debug', function() {
return {
restrict: 'E',
template: "scope {{$id}} loaded from {{source}}",
link: function($scope, el, attrs) {
$scope.source = attrs.source
if( attrs.autoApply ) {
// this works
$scope.$apply()
}
},
scope: true
}
})
// mimic an xhr request
setTimeout(function() {
var html = "<div><debug source='xhr (auto-applied)' auto-apply='1'></debug><br /><debug source='xhr'></debug></div>",
target = document.getElementById('target'),
$injector = angular.injector(['ng','app']),
$compile = $injector.get('$compile'),
$rootScope = $injector.get('$rootScope'),
$scope = angular.element(target).scope();
target.innerHTML = $compile(html)($scope)[0].outerHTML
// these do nothing, and I want to compile the directive's template from here.
$scope.$apply()
$scope.$root.$apply()
angular.injector(['ng','app']).get('$rootScope').$apply()
}, 0)
输出
scope 003 loaded from html
scope 005 loaded from xhr (auto-applied)
scope {{$id}} loaded from {{source}}
更新:解决方案适用于具有模板属性的指令,但不适用于 templateUrl
所以,我应该一直在编译 dom 节点,而不是 HTML 字符串。但是,如果指令包含 templateUrl,则此更新的小提琴显示相同的失败行为:
【问题讨论】:
标签: javascript jquery angularjs angularjs-scope angular-directive