所以我有机会获得一个REST API,我打,返回以下预生成的HTML返回:AngularJS:编译内部HTML指令通过API
<p class="p">
<sup id="John.3.16" class="v">16</sup>
<span class="wj">“For </span>
<span class="wj">God so loved </span>
<span class="wj">the world,</span>
<span class="wj">that he gave his only Son, that whoever believes in him should not </span>
<span class="wj">perish but have eternal life.</span>
</p>
这就提出了一个有趣的新挑战我学习AngularJS。我无法控制从API返回的HTML,因为它不是我创建的API。
我想要做的事(这可能是完全错误的做法)是在“v”类上构建一个类指令,以便我可以添加一个ng-click属性到经文编号并通过我的应用程序的另一部分的诗歌信息。
下面是我目前拥有的代码,虽然我认为它会做,但它似乎没有做任何事情。
var app = angular.module('ProjectTimothy');
app.filter("sanitize", ['$sce', function($sce) {
return function(htmlCode){
return $sce.trustAsHtml(htmlCode);
}
}]);
app.controller("timothy.ctrl.search", ['$scope', '$http', function($scope, $http){
$scope.url = "http://apiendpoint.com/";
$scope.copyright = "";
$scope.search = function() {
// Make the request to the API for the verse that was entered
// Had to modify some defaults in $http to get post to work with JSON data
// but this part is working well now
$http.post($scope.url, { "query" : $scope.searchwords, "version": "eng-ESV"})
.success(function(data, status) {
// For now I'm just grabbing parts of the object that I know exists
$scope.copyright = data.response.search.result.passages[0].copyright;
$scope.result = data.response.search.result.passages[0].text;
})
.error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}]);
app.directive("v", ['$compile', function($compile) {
return {
restrict: 'C',
transclude: true,
link: function(scope, element, attrs) {
element.html("<ng-transclude></ng-transclude>").show();
$compile(element.contents())(scope);
},
scope: { id:'@' },
/*template: "<ng-transclude></ng-transclude>",*/
replace: false
};
}]);
HTML模板被植入了由API返回的HTML:
<div class="bible_verse_search_container" ng-controller="timothy.ctrl.search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Bible Verse To Read (i.e. John 11:35)" ng-model="searchwords">
<span class="input-group-btn">
<button class="btn btn-default" type="button" ng-click="search()">Search</button>
</span>
</div>
<div class="well" ng-show="copyright" ng-bind-html="copyright | sanitize"></div>
<div ng-bind-html="result | sanitize"></div>
</div>
所以我希望会发生将是该HTML被填充到结合的HTML底部的div,然后以某种方式调用$ compile来将“v”类sup转换为我可以修改的指令。再一次,我对Angular来说很新,所以可能有一种超级简单的方法来做到这一点,就像Anguler中的其他事情一样,我还没有找到。
真的,最终目标是使每个节数转换为它自己的指令,能够使它可点击并访问ID属性,它有这样我就可以送一些用户内容的信息反馈给我自己的API。
这感觉就像很多的信息,所以让我知道,如果有什么不清楚。我会继续努力的,所以如果我先弄明白,我一定会更新一个答案。
IN PROGRESS
经过了这样一个问题:https://stackoverflow.com/a/21067137/1507210
现在我想知道它是否会更有意义,试图转换,其中的诗句显示为指令的部分,然后让搜索控制器用服务器中的HTML填充一个范围变量,然后用它作为指令的模板... think think think