Reputation: 9916
I have two directives. The outer directives needs to get some information from a service and then use that object for the inner directive. But I can't figure out how to do this correctly. Here's some sample code, in which I imagine I have some colored pencils, and we need to retrieve the pencil information based on the ID to figure out the pencil's color:
<div pencil-directive pencil-id="7"></div>
angular.module('app', [])
.controller('sampleController', function($scope){
$scope.color = "red";
})
.directive('colorDirective', function(){
return {
restrict: "E",
template: "<span ng-class='color'>{{color}}</span>",
scope: {
color: '='
}
}
})
.directive('pencilDirective', ["$timeout", function($timeout){
return{
restrict: "A",
template: "<div>Pencil {{pencilId}} is " +
"<color-directive color='pencil-color'> </div>",
scope: {
pencilId: "@",
pencilColor: "=?"
},
controller: function($scope){
//simulate getting the pencil color from a service
$timeout(function(){
$scope.pencilColor = "blue";
}, 10)
}
}
}])
I would expect that to look like this:
Pencil 7 color is blue.
But instead it ends up just looking like this:
Pencil 7 color is 0
I assume that's because pencilColor
isn't initalized by the time the colorDirective
sees it and it isn't updated later, but I don't know the "angular way" of making this work.
Here's a plunk. Note that I'm on Angular 1.2 since we're still supporting IE 8 (for now).
Upvotes: 1
Views: 48
Reputation: 4786
Your issue is the way your binding between your parent directive and child.
Your using scope.pencilColour
but passing it into your child directive with pencil-color
.
When using scope properties and attributes for your directives then the dash is needed. However when using them to bind with in your template. Either with {{}}
or passing them into a sub-directives attributes your do not need the dash and can use the scope property as defined.
So change <color-directive color='pencil-color'> </div>
to <color-directive color='pencilColor'> </div>
See plunk: http://plnkr.co/edit/mVCKLWgknwg81SUkIRtf?p=preview
EDIT: Not too sure if ive explained that very well maybe this will help.
<!--Here we need the dash as were referencing it as a html attribute-->
<div pencil-directive pencil-color="'green'"></div>
<!--However in the directives template when we bind we use it as defined on our scope-->
{{pencilColor}}
<!--Even when passing it into a sub directive. The sub directives attribute needs the dash but our current one doesn't.-->
<sub-directive sub-prop="pencilColor" />
Upvotes: 2