Reputation: 121
I have created a directive and passed attribute as object(name/value pair) of string. However if i try to access the attribute value inside the template, it is not getting evaluated. The attribute is passed like below
<testcomponent myInfo="{firstname:'green',lastname:'Woods'}"></testcompone>
The template is define like below
template: '<div>This will not run fine..! </div>'+
'<div> This first name is: {{myInfo.firstname}} </div>',
I have created an islolated scope like below
scope: {
info: '=myInfo',
},
The jsfiddle is @https://jsfiddle.net/visibleinvisibly/be4ww6vu/
The variable({{myInfo.firstname}}) needs to be evaluated but it is not happening.I am looking for a solution which doesnt need to create a controller(i am be wrong too)
Thanks in advance, jason
Upvotes: 1
Views: 1123
Reputation: 26150
There are a few problems (identified below) and a few tips for using Angular as well.
myInfo
in your directive, then in the markup you need to set it as my-info
. Angular automatically adapts the name from my-info
in the markup into myInfo
in the directive.myInfo
, however your scope declaration assigns that to the scope variable info
. In order to output the name, you need to change it to {{info.firstname}}
.Below is the revise code, with comments:
<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>
And the directive:
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) {
}
};
});
Lastly - normally (in my experience) you would not set the value of the attribute directly in the markup, but rather you would reference a $scope
variable from your controller, and assign the value in your controller.
Upvotes: 2