有幾個問題(如下所示)以及使用Angular的一些技巧。
Here's a working fiddle
- 角是大小寫敏感的,而 「特別」 有關的屬性名稱。如果您希望您的指令中的屬性爲
myInfo
,那麼在標記中,您需要將其設置爲my-info
。 Angular會自動將標記中的my-info
的名稱改爲指令中的myInfo
。
- 您的標記(您試圖輸出名稱的位置)引用
myInfo
,但是您的範圍聲明將其分配給範圍變量info
。爲了輸出名稱,您需要將其更改爲{{info.firstname}}
。
下面是修改代碼,以註釋:
<div ng-app="testApp" >
<!-- Issue #2: If you want camel-case "myInfo", angular expects the attribute to be "my-info". -->
<test-component
my-info="{firstname: 'green',lastname: 'Woods'}"/>
</div>
而且指令:
var module = angular.module('testApp', [])
.directive('testComponent', function() {
return {
restrict: 'E',
// Issue #1: The template referenced 'myInfo', but your scope was assigning that to 'info'.
template: '<div>This will not run fine..! </div>'+
'<div> This first name is: {{info.firstname}} </div>',
scope: {
/* Hints:
= is two way-binding "deep" watch.
=* is "shallow" watch, and on this simple object, that is all you need.
@ is text-binding (for reference)
*/
info: '=*myInfo',
},
controller: function($scope) {
},
link: function (scope, element, attrs) {
}
};
});
最後 - 正常(在我的經驗),你不會設置該屬性的值直接在標記中,而是從控制器引用$scope
變量,並在控制器中分配值。
我寧願建議您創建一個名稱值對的數組,並在屬性值中傳遞數組的名稱。試試這個,讓我知道如果這個作品 –
謝謝你創建一個小提琴。大大簡化了回答! –
又一個快速提示 - 在您的小提琴中,您使用的是Angular 1.0 - 我希望您實際使用/能夠使用1.4+?有一些分歧會讓你受益。 (2.0是不同的,所以如果你正在學習角度,你可能想考慮學習2) –