在Angular指令中初始化@attr

时间:2013-07-31 12:23:50

标签: angularjs angularjs-directive angularjs-scope

我有这样的指示: 你可以在这里看到等效的plunker http://plnkr.co/edit/0e2nMyatAMD3M3QTCtls

app.directive('bpTest', function() {
  return {
    restrict: 'A',
    templateUrl: 'directiveTemplate.html',
    scope: {
      bpType: '@'
    },
    link: function($scope, $elem, $attrs) {
      console.log($scope, $elem, $attrs);
      $scope.bpType = $scope.bpType || 'text';
    }  // link function
  };
});

在directiveTemplate.html中:

<div>
  {{ bpType }}
</div>

在index.html中:

<div bp-test bp-type="text"></div>  <!-- results in <div>text</div> -->
<div bp-test bp-type="number"></div>  <!-- results in <div>number</div> -->
<div bp-test></div>  <!-- results in <div></div> ????? -->

由于我初始化$scope.bpType = $scope.bpType || 'text',我希望第三个指令<div bp-test></div>显示<div>text</div>,但它只是吐出<div></div>

我误解/做错了什么?

谢谢!

2 个答案:

答案 0 :(得分:2)

范围绑定的发生时间晚于第一次调用链接函数,因此您需要观察该属性以设置默认值。

$scope.$watch("bpType", function(value) {
  $scope.bpType = value || 'default';
});

答案 1 :(得分:0)

您的链接功能应如下所示:

scope: {  
},
link: function(scope, elem, attrs) {
      scope.bpType = attrs.bpType || 'text';
} 

注意$ attrs.bpType而不是$ scope.bpType 此外,按惯例链接函数中的参数不应使用$ prefix命名,因为它们是函数参数,而不是注入依赖项。