2013-07-31 58 views
1

我有這樣的指令: 你可以在這裏看到的等效plunker http://plnkr.co/edit/0e2nMyatAMD3M3QTCtls在角指令初始化@attr

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',我預計t他第三個指令<div bp-test></div>顯示<div>text</div>,但它只是吐出<div></div>

我誤解/做錯了什麼?

謝謝!

回答

2

作用域綁定發生的時間要晚於對鏈接函數的第一次調用,因此您需要注意屬性以設置默認值。

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

不錯!那就是訣竅。感謝你及時的答覆。 –

0

你的鏈接功能應該是這樣的:

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

通知$ attrs.bpType不是$ scope.bpType 此外,在按照慣例鏈接功能參數不應該與$前綴命名的那些功能是參數,而不是注入的依賴關係。