[英]Bound attribute empty in an angular directive
我有一個簡單的指令
'use strict';
angular.module('ludaooApp')
.directive('rating', function () {
return {
templateUrl: 'app/rating/rating.html',
restrict: 'EA',
link: function (scope, element, attrs) {
scope.mark = attrs.mark;
console.log(attrs);
};
})
該指令僅記錄指令的屬性。
這是我使用該指令的方式:
<rating mark="{{game.rating}}" style="font-size: 30px"></rating>
這是Web檢查器的結果:
如您所見,第一行的mark是空的mark=""
。 但是之后,將其填充為值mark="4.16"
。
結果是,如果我console.log(scope.mark)
,我看到的是0而不是4.16。
我認為是因為從數據庫中檢索了4.16,並且在控制器中初始化{{game.rating}}
之前執行了代碼。
所以問題是,如何處理這個問題? 以及如何訪問“ 4.16”?
嘗試在服務中使用角度承諾,該角度承諾從api接收數據,然后將延遲對象的狀態傳遞給ng-if-此決定可以幫助擱置評級指令的呈現。
簡單的例子:
<div ng-app="ludaooApp">
<div ng-controller="GameCtrl as game">
<rating mark="{{game.rating}}" ng-if="game.$promise.status"></rating>
</div>
</div>
(function(angular){
"use strict";
angular.module('ludaooApp',[])
.controller('GameCtrl', ['$timeout', '$q', function($timeout, $q){
var game = this;
var deferred = $q.defer()
game.$promise = deferred.promise.$$state
$timeout(function(){
game.rating = 4.16;
deferred.resolve();
},3);
}])
.directive('rating', function () {
return {
restrict: 'EA',
link: function (scope, element, attrs) {
scope.mark = scope.$eval(attrs.mark);
console.log(attrs);
}
};
})
})(window.angular);
我相信您的指令將在{{game.rating}}
完成綁定之前創建。
嘗試使用ngAttr
以便僅在綁定完成后定義您的屬性:
<rating ng-attr-mark="{{game.rating}}" style="font-size: 30px"></rating>
我認為Enver的解決方案可能有效,但過於復雜。 問題是由game.rating引起的,閱讀時尚未完全綁定。 一個更簡單的解決方案是等到game.rating綁定完全完成並分配給mark屬性后,如下所示:
link: function (scope, element, attrs) {
attrs.$observe("mark", function(value) {
// read "mark" here
console.log(attrs.mark);
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.