我创建了一个指令并将属性作为字符串的对象(名称/值对)传递。但是,如果我尝试访问模板中的属性值,则不会对其进行评估。 该属性传递如下
<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}})需要进行评估但是没有发生。我正在寻找一个不需要创建控制器的解决方案(我也错了)
提前致谢, 杰森
答案 0 :(得分:2)
有一些问题(如下所示)以及使用Angular的一些提示。
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
变量,并在控制器中指定值。 / p>