我创建了一个指令,并将属性作为字符串的对象(名称/值对)传递。但是,如果我试图访问模板中的属性值,则不会对其进行评估。属性传递如下所示
<testcomponent myInfo="{firstname:'green',lastname:'Woods'}"></testcompone>
模板定义如下所示
template: '<div>This will not run fine..! </div>'+
'<div> This first name is: {{myInfo.firstname}} </div>',
我创建了一个孤岛范围,如下所示
scope: {
info: '=myInfo',
},
jsfiddle是@https://jsfiddle.net/visibleinvisibly/be4ww6vu/
变量({{myInfo.firstname}})需要评估,但它没有发生,我正在寻找一个不需要创建控制器的解决方案(我也错了)
谢谢你,杰森
发布于 2016-04-30 13:04:21
这里有一些问题(以下所述)和一些使用角度的提示。
myInfo
,则需要在标记中将其设置为my-info
。角自动调整从标记中的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
变量,并在控制器中分配值。
https://stackoverflow.com/questions/36955075
复制相似问题