我正在尝试编写我的第一个 AngularJS 指令;它基本上是一段代码,可以从最大数量的星星中模糊出一定数量的星星(徽章)。
指令中的 link: function() 代码似乎无法访问传入的非静态值的范围变量(尽管模板代码可以)。
我需要将链接:代码放在别处吗?
html:
<span class="badge"><span sa-motes mote-count="character.attributes.stamina.value" mote-max="5" stat-name="character.attributes.stamina.name"></span> </span>
mote-max="5"使我成为 i,但 mote-count="character.attributes.stamina.value"却没有。 (在范围内显示为 null
Angular 色....数据已加载到此部分的 Controller 中。
指令:
sistemaDirectives.directive('saMotes', function() {
return {
restrict: 'A',
scope: {
moteCount: '=',
moteMax: '=',
statName: '@'
},
template: '<span ng-repeat="mote in motes" class="glyphicon glyphicon-certificate" ng-class="{\'mote-empty\':$index>moteCount+1}"> </span>',
link: function(scope, elem, attrs, ctrl ) {
scope.motes = [];
for (var i = 0; i< scope.moteMax; i++) {
scope.motes.push( i );
}}}});
我在我看来尝试了这段内联代码,它起作用了:
<span class="badge">
<span class="glyphicon glyphicon-certificate" ng-repeat="i in getNumber(character.attributes.strength.value) track by $index"></span><span class="glyphicon glyphicon-certificate mote-empty" ng-repeat="i in getNumber(character.attributes.strength.max - character.attributes.strength.value) track by $index">
</span></span>
getNum 函数只是创建一个数组(在 Controller 中):
$scope.getNumber = function(num) {
return new Array(num);
}
帮忙吗?
最佳答案
如果我理解正确的话,你是说 scope.moteCount 在链接函数中不可用,而它应该是。 只要 character.attributes.stamina.value 具有有效值。
看看这个Fiddle仅使用警报来显示 moteCount 的值。
我刚刚拿了你的代码并启动了周围的 Controller
$scope.character = {attributes: {stamina: {value: 10, name: 'theName'}}};
更新
由于您正在获取异步传递给指令的值,因此在执行链接函数时它们可能尚未准备好。在链接函数中使用 watch ,以便在数据准备就绪时得到通知
scope.$watch('mouteCount',function(newValue, oldValue){
if(newValue !== oldValue){
console.log({label:'watch', value: scope.mouteCount});
}
});
关于javascript - AngularJS 指令绑定(bind)链接 : has no access to scope variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25152862/