I want to implement a like widget for different kind of documents. I tried to use a scope data to generate template html code, here is what I've done:
angular.module('app.common')
.directive('like',['favoritesResource','session','$q', like]);
function like(favoritesResource, session, $q, $scope) {
var news = $q.defer();
function link(scope, el) {
//console.log(scope);
news.resolve(scope.vm.theNews);
};
function getTemplate(el, attrs) {
loadNews().then(function(news) {
console.log(news);
favoritesResource.isLike(session.getCurrentUser.id, {docType: news.type, docId: news.id}, function(status) {
if (status == 'like'){
return '<button class="fa fa-heart" ng-click="vm.likeIt()">like</button>';
}else {
return '<button class="fa fa-heart-o" ng-click="vm.likeIt()">like</button>'
}
});
});
};
function loadNews() {
return news.promise;
}
return {
link: link,
restrict: 'E',
template: getTemplate(),
replace: true
};
}
I found the "news" object can be printed in the console, but the result html is <like></like>, not <button class="fa fa-heart" ng-click="vm.likeIt()">unlike</button> or <button class="fa fa-heart-o" ng-click="vm.likeIt()">like</button>, could anyone tell me what's wrong? Or do you have any suggestion to write such widget?
UPDATE:
This widget is within a controller used to show document content, here is my controller:
angular
.module('app.news')
.controller('ReadNewsController', ReadNewsController);
ReadNewsController.$inject = ['theNews', '$scope', 'favoritesResource', 'session'];
function ReadNewsController(theNews, $scope, favoritesResource, session) {
var vm = this;
vm.theNews = theNews;
vm.likeIt = function() {
favoritesResource.like(session.getCurrentUser.id, {docType:theNews.type, docId: theNews.id});
};
vm.unlikeIt = function() {
favoritesResource.disLike(session.getCurrentUser.id, {docType:theNews.type, docId: theNews.id});
};
vm.isLikeIt = function() {
favoritesResource.isLike(session.getCurrentUser.id, {docType:theNews.type, docId: theNews.id});
};
}
and the routes:
var module = angular.module('app.news', ['ui.router', 'app.common', 'app.data']);
module.config(appConfig);
appConfig.$inject = ['$stateProvider'];
function appConfig($stateProvider) {.state('app.readNews', {
url: '/news/read/:id',
templateUrl: 'app/modules/news/read/news.html',
controller: 'ReadNewsController as vm',
resolve: {
theNews: function(newsResource, $stateParams) {
return newsResource.get({id: $stateParams.id}).$promise.then(function(item){
item.type = 'news'; //for 'like' directive
return item;
})
}
}
})
getTemplate()method returns before the function in thethen()function gets executed since it is asynchronous..then