從數(shù)據(jù)庫編譯動態(tài)HTML字符串形勢嵌套在我們的角度應用程序中的是一個名為Page的指令,它由一個控制器支持,其中包含一個帶有ng-bin-html-不安全屬性的div。這被分配給一個名為‘pageContent’的$Scope var。這個var從數(shù)據(jù)庫中得到動態(tài)生成的HTML。當用戶切換到下一頁時,將調(diào)用DB,并將pageContent var設置為這個新的HTML,該HTML通過ng-bind-html-不安全在屏幕上呈現(xiàn)。下面是代碼:頁指令angular.module('myApp.directives')
.directive('myPage', function ($compile) {
return {
templateUrl: 'page.html',
restrict: 'E',
compile: function compile(element, attrs, transclude) {
// does nothing currently
return {
pre: function preLink(scope, element, attrs, controller) {
// does nothing currently
},
post: function postLink(scope, element, attrs, controller) {
// does nothing currently
}
}
}
};
});頁面指令模板(“page.html”來自上述templatUrl屬性)<div ng-controller="PageCtrl" >
... <!-- dynamic page content written into the div below -->
<div ng-bind-html-unsafe="pageContent" >
...</div>頁控制器angular.module('myApp')
.controller('PageCtrl', function ($scope) {
$scope.pageContent = '';
$scope.$on( "receivedPageContent", function(event, args) {
console.log( 'new page content received after DB call' );
$scope.pageContent = args.htmlStrFromDB;
});});這很管用。我們在瀏覽器中很好地呈現(xiàn)了來自DB的頁面HTML。當用戶切換到下一頁時,我們會看到下一頁的內(nèi)容,依此類推。到目前一切尚好。問題這里的問題是,我們希望在頁面內(nèi)容中包含交互式內(nèi)容。例如,HTML可能包含一個縮略圖,當用戶單擊它時,角應該做一些很棒的事情,例如顯示彈出模式窗口。我已經(jīng)在我們的數(shù)據(jù)庫中的HTML字符串中放置了角方法調(diào)用(ng-click),但當然角不會識別任何方法調(diào)用或指令,除非它以某種方式解析HTML字符串、識別它們并編譯它們。
3 回答

拉風的咖菲貓
TA貢獻1995條經(jīng)驗 獲得超2個贊
scope.$watch(attrs.dynamic, function(html) {
attrs.dynamic
scope: { dynamic: '=dynamic'},
angular.module('app') .directive('dynamic', function ($compile) { return { restrict: 'A', replace: true, scope: { dynamic: '=dynamic'}, link: function postLink(scope, element, attrs) { scope.$watch( 'dynamic' , function(html){ element.html(html); $compile(element.contents())(scope); }); } }; });

慕仙森
TA貢獻1827條經(jīng)驗 獲得超8個贊
var $injector = angular.injector(['ng', 'myApp']);$injector.invoke(function($rootScope, $compile) { $compile(element)($rootScope);});
添加回答
舉報
0/150
提交
取消