I have a view partial "nameplate.jade" that has a couple attributes bound from a user object. On another page I want to see a list of users as seen by their nameplates. So what I would like to do is somehow send either the user or user._id I'll have from whatever controller I'm in and have it render the nameplate, and then go on to rendering the next one with the first one persisting.
How I'd use it for one nameplate
div(ng-controller="LoginCtrl")
div(ng-show="logged_in()")
a(href="/profile/{{ currentUser.handle }}")
nameplate(user="{{currentUser}}")
How I'd use it if I wanted a list of nameplates
div(ng-repeat="participant in event.participants")
nameplate(userid="participant.userid")
nameplate.jade
.nameplate
.imageColumn
.image
img(src="{{ user.avatar }}")
.otherColumn
.nameRow
a(ng-href="/profile/{{ user.handle }}") {{ user.handle }}
nameplate directive
.directive('nameplate', (User) ->
restrict: 'E'
replace: true
scope:
user: '@currentuser'
userid: '@userid'
templateUrl: '/partials/nameplate'
link: (scope, elems, attrs) ->
# I've tried a lot of things that didn't work here
I was using user: '@currentuser'
but I should have been using user: '¤tuser'
The key was in my directive's scope hash
.directive('nameplate', () ->
restrict: 'E'
replace: true
scope:
user: '¤tuser'
templateUrl: '/partials/nameplate'
link: (scope, elems, attrs) ->
scope.$watch scope.user, (_user) ->
scope.user = _user
)
I was trying to get the {{currentUser}}, but it kept executing in the isolated scope and wasn't updating when the parent scope's currentUser changed. So using the 'scope.$watch' to listen for value changes and using &
instead of @
solved my problems
From Angularjs Directive Guide
scope - If set to: {} (object hash)
- & or &attr - provides a way to execute an expression in the context of the parent scope
EDIT
And to elaborate on Andy's comment below, you can reduce the directive syntax to this:
.directive('nameplate', () ->
restrict: 'E'
replace: true
scope:
user: '=currentuser'
templateUrl: '/partials/nameplate'
)
With my use case I don't even need to specify a link function