I am trying to use angularJS to load contents of my HTML from ajax calls. I would like to have a single method with different parameters to vary ajax/REST uri and display results in different components. The (non-running version) code looks something like this:
app.controller('ContentController', function($scope, $sce, $http) {
$scope.FetchContent = function(pageId) {
let contentUri = 'https://somewhere/restendpoint/?id=' + pageId;
$http.get(contentUri).then(function(data) {
return $sce.trustAsHtml(data.data.d[0].Content);
}
}
})
<div ng-controller="ContentController" class="row">
<div class="col-md-4" ng-bind-html="FetchContent('home')"></div>
<div class="col-md-4" ng-bind-html="FetchContent('welcome')"></div>
<div class="col-md-4" ng-bind-html="FetchContent('contact')"></div>
</div>
I end up getting tons of ajax calls generated from this. I've tried creating a custom directive, but it updates all elements with same data. Can anyone give me a pointer? Thanks!!
So.. I was able to get around the repeating ajax calls by using directives instead, and had to embed element Id to lock down the element:
app.controller('ContentController', function($scope, $sce, $http) {
$scope.FetchContent = function(pageName, elem) {
var contentUri = 'https://somecontent/restendpoint/?id=' + pageName;
$http.get(contentUri).then(function (data) {
$('#' + elem).html(data.data.d[0].HTMLContent);
});
}
});
app.directive('loadcontent', function($parse) {
return {
restrict: 'A',
link: function ($scope, elem, attrs) {
elem.ready(function() {
$scope.$apply(function() {
var func = $parse(attrs.loadcontent);
func($scope, elem)
});
});
}
};
});
<div ng-controller="ContentController" class="row">
<div class="col-md-4" id="e1" loadcontent="FetchContent('home', 'e1')"></div>
<div class="col-md-4" id="e2" loadcontent="FetchContent('home', 'e2')"></div>
<div class="col-md-4" id="e3" loadcontent="FetchContent('home', 'e3')"></div>
</div>
It works and it inserts unique contents into own elements, but I really don't like the way and can't help but think there's gotta be a better and proper ways to do this... Any ideas from angularJS gurus?