2016-04-30 70 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 - 很高兴我可以帮助。如果此答案解决了您的问题,请点击答案左侧的复选标记以接受答案。 –