AngularJS指令绑定链接:无法访问作用域变量

3

我正在尝试编写我的第一个AngularJS指令;它基本上是一段代码,可以在最大星号数量内呈现出一定数量的星号(徽章)。

指令中的链接:函数似乎无法访问传入的作用域变量,除非它们是静态值(尽管模板代码可以)。

我需要把链接:代码放在其他地方吗?

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"可以实现,但mote-count="character.attributes.stamina.value"无法实现(在作用域中显示为空)。

该局部控制器已加载角色数据。

指令:

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函数只是在控制器中创建一个数组:

$scope.getNumber = function(num) {
    return new Array(num);   
}

Help?


匿名函数在指令中的 link 下是否有意将参数命名为 scope 而不是 $scope - Nick McCurdy
@NicolasMcCurdy 是的,链接函数的参数没有像控制器那样被注入。 - pixelbits
你有一个 JSFiddle 吗? - pixelbits
据我了解,link: 传递了特定的作用域,不应使用 $scope - 我正在从 angularjs 网站复制示例。 - Pól
除非作用域变量被传递为文字,例如:mote-count="5",而不是对象的计算结果,比如mote-count="myobject.property",否则mote-count是可用的。 - Pól
1个回答

1
如果我理解正确,您说在链接函数中无法使用scope.moteCount,并且应该可以使用。只要character.attributes.stamina.value具有有效值。
请查看这个Fiddle,它仅使用警报显示moteCount的值。
我只是使用您的代码并启动了周围的控制器。
$scope.character = {attributes: {stamina: {value: 10, name: 'theName'}}};

更新

由于您异步获取传递给指令的值,因此当执行链接函数时它们可能还没有准备好。在链接函数中使用监视器,在数据准备就绪时获得通知。

  scope.$watch('mouteCount',function(newValue, oldValue){
    if(newValue !== oldValue){
      console.log({label:'watch', value: scope.mouteCount});
    }
  });

character.attributes...等内容在控制器中通过$http(从本地json文件)加载。它正在模板中进行评估,但是console.log和调试显示在link:function中它是未定义的。如果我将字符串值传递到作用域中(character.attributes.stamina.name,即“Stamina”),则在link:function中它是字符串文字“character.attributes.stamina.name”,但是如果我在部分中评估它 - 或者在指令的模板中! - 它会显示其值(即“Stamina”)。 - Pól
哇塞!就是这样了!非常感谢你!跟进问题:我应该在其他地方做这件事吗,比如指令的控制器中?还是我可以告诉指令等待数据加载完成?我只是不想在我的代码中到处都这样写... - Pól
很难对你的问题给出一个通用的答案。关于这个主题有很多文章,比如这篇文章http://jensrantil.github.io/refreshable-angularjs-service.html。 - Edminsson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接