2016-04-30 72 views
1

我創建了一個指令並傳遞了屬性作爲字符串的對象(名稱/值對)。但是,如果我嘗試訪問模板內的屬性值,它不會得到評估。 屬性被傳遞像下面在Angularjs模板中訪問屬性值

<testcomponent myInfo="{firstname:'green',lastname:'Woods'}"></testcompone> 

該模板是定義像下面

template: '<div>This will not run fine..! </div>'+ 
     '<div> This first name is: {{myInfo.firstname}} </div>', 

我已經創建了一個islolated範圍如下面

scope: { 
     info: '=myInfo', 
    }, 

的的jsfiddle是@https://jsfiddle.net/visibleinvisibly/be4ww6vu/

變量({{myInfo.firstname}})需要是e計價,但它不是happening.I要尋找其犯規需要創建一個控制器解決方案(我是錯的太)

在此先感謝,傑森

+0

我寧願建議您創建一個名稱值對的數組,並在屬性值中傳遞數組的名稱。試試這個,讓我知道如果這個作品 –

+0

謝謝你創建一個小提琴。大大簡化了回答! –

+0

又一個快速提示 - 在您的小提琴中,您使用的是Angular 1.0 - 我希望您實際使用/能夠使用1.4+?有一些分歧會讓你受益。 (2.0是不同的,所以如果你正在學習角度,你可能想考慮學習2) –

回答

2

有幾個問題(如下所示)以及使用Angular的一些技巧。

Here's a working fiddle

  1. 角是大小寫敏感的,而 「特別」 有關的屬性名稱。如果您希望您的指令中的屬性爲myInfo,那麼在標記中,您需要將其設置爲my-info。 Angular會自動將標記中的my-info的名稱改爲指令中的myInfo
  2. 您的標記(您試圖輸出名稱的位置)引用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變量,並在控制器中分配值。

+0

感謝它的工作.. – visibleinvisibly

+0

@visibleinvisibly - 很高興我可以幫助。如果此答案解決了您的問題,請點擊答案左側的複選標記以接受答案。 –