Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  90] [ 3]  / answers: 1 / hits: 46779  / 11 Years ago, fri, january 17, 2014, 12:00:00

I am having issues getting my directive to render its content only after my promise has been resolved. I thought then() was supposed to do this but it doesn't seem to be working..



Here is my controller:



// Generated by CoffeeScript 1.6.3
(function() {
var sprangularControllers;

sprangularControllers = angular.module('sprangularControllers', ['sprangularServices', 'ngRoute']);

sprangularControllers.controller('productsController', [
'$scope', '$route', '$routeParams', 'Product', 'Taxonomy', function($scope, $route, $routeParams, Product, Taxonomy) {
Taxonomy.taxonomies_with_meta().$promise.then(function(response) {
return $scope.taxonomies = response.taxonomies;
});
return Product.find($routeParams.id).$promise.then(function(response) {
return $scope.currentProduct = response;
});
}
]);

}).call(this);


My directive:



// Generated by CoffeeScript 1.6.3
(function() {
var sprangularDirectives;

sprangularDirectives = angular.module('sprangularDirectives', []);

sprangularDirectives.directive('productDirective', function() {
return {
scope: {
product: '='
},
templateUrl: 'partials/product/_product.html',
link: function(scope, el, attrs) {
console.log(scope);
console.log(scope.product);
return el.text(scope.product.name);
}
};
});

}).call(this);


Scope returns okay, and when I check it in dev tools scope.product is not undefined however I am presuming that is because by the time I check it the promise has been resolved?



console.log(scope.product) however, returns undefined..


More From » angularjs

 Answers
6

Because your value is asynchronously populated, you'll want to add a watch function that updates your bound element.



  link: function(scope, el, attrs) {
scope.$watch('product', function(newVal) {
if(newVal) { el.text(scope.product.name);}
}, true);
}


You could also move a lot of complexity into a directive controller and use the link function for manipulating the DOM only.



The true third parameter to $watch causes a deep watch, since you're binding this directive to a model.



Here are a couple of links with good examples:

http://www.ng-newsletter.com/posts/directives.html

http://seanhess.github.io/2013/10/14/angularjs-directive-design.html


[#73111] Thursday, January 16, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neob

Total Points: 253
Total Questions: 106
Total Answers: 104

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
;