在承诺解决之前正在呈现指令 [英] Directive is being rendered before promise is resolved
问题描述
只有在我的承诺得到解决后,我才能让我的指令呈现其内容.我认为 then()
应该这样做,但它似乎不起作用..
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..
这是我的控制器:
// 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);
我的指令:
// 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 返回正常,当我在开发工具中检查它时 scope.product
不是未定义的,但我认为这是因为当我检查它时,承诺已经解决?
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)
但是,返回 undefined..
console.log(scope.product)
however, returns undefined..
推荐答案
由于您的值是异步填充的,您需要添加一个监视函数来更新您的绑定元素.
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);
}
您还可以将很多复杂性转移到指令控制器中,并使用链接函数仅操作 DOM.
You could also move a lot of complexity into a directive controller and use the link function for manipulating the DOM only.
$watch
的第三个参数 true
导致深度观察,因为您将此指令绑定到模型.
The true
third parameter to $watch
causes a deep watch, since you're binding this directive to a model.
这里有几个带有很好例子的链接:
http://www.ng-newsletter.com/posts/directives.html
http://seanhess.github.io/2013/10/14/angularjs-directive-设计.html
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
这篇关于在承诺解决之前正在呈现指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!