I have been working with a REST API that returns pre-generated HTML like this:
<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>
This has posed a new challenge for me in learning AngularJS. Since I can't control the HTML from the API, I wanted to build a class directive on the "v" class to enable an ng-click attribute on the verse number and pass the verse information to another part of my application.
Here is the current code I have, which doesn't seem to be functioning as expected:
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() {
$http.post($scope.url, { "query" : $scope.searchwords, "version": "eng-ESV"})
.success(function(data, status) {
$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 template populated with the returned 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>
I hope to populate the bottom div with HTML containing clickable verse numbers by converting them into directives. My goal is to make each verse number clickable and extract the ID attribute to send it along with user content back to my API.
If anything is unclear, please let me know. I'll continue working on this and update if I find a solution.
IN PROGRESS
Referenced this question for guidance:
I'm contemplating whether converting the verse display section into a directive and having the search controller populate a scope variable with server HTML as the directive template would be a better approach... thinking hard!