I am trying to pass an object from a controller via my HTML template to a directive to use the object in another HTML template.
I got an controller with:
function controller($state, $rootScope) {
var vm = this;
vm.residents = [object];
}
In my config:
function config($sateprovider) {
[..],
templateUrl: [..]/template.html,
[..]
}
In the templtate.html I got:
<div ng-repeat="resident in controller.residents>
<user-block user={{ resident }}></user-block>
</div>
In my user block directice I got:
function userBlock() {
restrict: 'E',
templateUrl: [..]/userblock.html,
controller: 'blockController',
controllerAs: 'blockCtrl',
bindTocController: true,
replace: true,
scope: {
user: '@',
}
}
And finaly in userblock.html:
<div>{{ blockCtrl.user }}</div>
I got the following output:
{"username":"Xiduzo","user_id":123,"experience":123456789,"total_energy":100,"energy_left":50,"rupees":[{"name":"emerald","amount":106},{"name":"sapphire","amount":43},{"name":"amethyst","amount":131},{"name":"ruby","amount":11},{"name":"citrine","amount":159},{"name":"coal","amount":23}]}
But when I want to get the username and do like:
<div>{{ blockCtrl.user.username }}</div>
I got no output at all.
Is there something I am missing or doing completely wrong?
Essentially the issue is you are using @
binding(one way binding) by which you are passing user
object to directive isolated scope. But the thing is @ coverts any type of varible in a string. So when user varible arrives to the directive scope
it is not pure user object
. Its nothing but stringified version of user JSON object.
That's why when you are trying to access it like JSON didn't worked.
I'd recommend you to pass that field using =
(two way binding) will make it working and persist type of object.
Change
scope: {
user: '@',
}
To
scope: {
user: '=',
}
And
<user-block user=resident></user-block>