我有以下 Angular 设置:
var app = angular.module('app', []);
app.filter('unsafe', function($sce) {
return $sce.trustAsHtml;
});
app.controller('SearchController', ['$scope', '$http', function($scope, $http) {
$scope.searchString = '';
$scope.searchType = 'Artist';
$scope.updateHtml = function() {
$http.get('/search', {
params: {
searchString: $scope.searchString,
searchType: $scope.searchType
}
}).success(function(data) {
$scope.html = data;
}).error(function(err){
$scope.html = err;
});
};
$scope.updateHtml();
}]);
app.directive('searchDirective', function() {
return {
restrict: 'A',
transclude: true,
template: '<div ng-bind-html="html | unsafe" ng-transclude></div>'
};
});
它通过 Controller 中的ajax提取原始html标记并将其存储在@scope.html
中。在指令中,该 html 通过 ng-bind-html 插入到 DOM 中。
html( Jade )如下所示:
#search(ng-controller="SearchController" search-directive)
它基本上可以工作。但在包含的这个 html 中,我有一些透明的内容,例如我想要解析的 {{searchType}}
。不幸的是,事实并非如此,它在浏览器中显示“{{searchType}}”。我可以改变什么来使嵌入工作?
我阅读了有关 $compile
和 $transclude
的内容,但我不知道如何使用它,也不知道它是否可以帮助我解决我的问题。谢谢!
最佳答案
在帕特里克的帮助下,我解决了这个问题。我将 Controller 更改为
app.controller('SearchController', ['$scope', '$http', '$interpolate',
function($scope, $http, $interpolate) {
$scope.searchString = '';
$scope.searchType = 'Artist';
$scope.updateHtml = function() {
$http.get('/search', {
params: {
searchString: $scope.searchString,
searchType: $scope.searchType
}
}).success(function(data) {
$scope.html = $interpolate(data)($scope); // <<-- difference here
}).error(function(err){
$scope.html = err;
});
};
$scope.updateHtml();
}]);
现在我的 html 是根据传入的范围进行插值的。谢谢!
编辑:
$interpolate
仅用于渲染 DOM 并通过范围解析它。它只是返回纯 html。如果您需要实际检索完整的工作 html 模板,其中包含 Angular 代码,请使用 $compile
。我发现this answer对于解决 $interpolate
、$compile
和 $parse
之间的差异非常有帮助。
关于javascript - Angular : using transclude with ng-bind-html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27365352/