javascript - AngularJS 指令绑定(bind)链接 : has no access to scope variables

标签 javascript angularjs angularjs-scope directive

我正在尝试编写我的第一个 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/

相关文章:

php - 如何在页面中仅显示 javascript 消息

javascript - 使用 Angular 将图像作为表单的一部分上传

javascript - 有没有办法将数据加载到脚本中

javascript - $scope.$on ('$destroy' , ...) 的事件处理程序是否被销毁?

angularjs - AngularJS 加载完成时发送事件

javascript - 无法在 javascript onreadystatechange 中读取自定义 http header ?

javascript - 在 JS 中获取过滤后的对象数组的最大值

javascript - 变量在 $scope 中可见,但在 Angular 中实际访问时未定义

javascript - tablesorter pager 插件 - 默认显示所有条目

javascript - Angular 2 模板的元素引用无法正常工作