我遇到了问题,我的指令只有在我的诺言得到解决后才能呈现其内容。我以为then()
应该这样做,但是似乎没有用。
这是我的控制器:
// 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.product
并没有定义,但是我想这是因为到我检查它时,诺言已经解决了吗?
console.log(scope.product)
但是,返回undefined。
因为您的值是异步填充的,所以您需要添加一个监视函数来更新绑定的元素。
link: function(scope, el, attrs) {
scope.$watch('product', function(newVal) {
if(newVal) { el.text(scope.product.name);}
}, true);
}
您还可以将很多复杂性转移到指令控制器中,并使用链接功能仅操作DOM。
在true
以第三个参数$watch
引起了深刻的手表,因为你这种绑定指令的典范。
以下是一些带有示例的链接:
http : //www.ng-newsletter.com/posts/directives.html
http://seanhess.github.io/2013/10/14/angularjs-directive-design.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句