admin管理员组文章数量:1419573
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
2 Answers
Reset to default 3The 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.
本文标签: javascriptHow to apply an AngularJS directive to ajax contentStack Overflow
版权声明:本文标题:javascript - How to apply an AngularJS directive to ajax content? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745314011a2653066.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论