I am binding an object to the scope of the directive and based on the value of status property of the object, directive will show or hide a menu.
Everything works fine if this object is created and available to the controller prior to passing it to the directive. However, when I change the code to retrieve this object from the server, the conditional statement fails claiming property status is undefined.
Remote object is retrieved in my controller using resource wrapped in service:
var reservation = Reservation.get({id: $routeParams.id}, function(){
$scope.reservation = reservation;
});
Service looks like this:
services.factory('Reservation', ['$resource', 'AppSettings', '$log',
function($resource, AppSettings, $log){
return $resource(AppSettings.serverUrl + '/reservations/:id', {}, {
update: {method:'PUT', params: {id: '@id'}}
});
}
]);
I almost positive this happens because the directive loads before the object is retrieved via resource. Is there a way to execute directive's controller only once the object is loaded? Below is my simplified, working code that uses locally created object.
Html:
<div ng-app="test">
<div ng-controller="testCtrl">
<p>Id: {{reservation.id}}</p>
<p>Name: {{reservation.name}}</p>
<p>Status: {{reservation.status.value}}</p>
<menu reservation="reservation"/>
</div>
</div>
Js
angular.module('test', []).factory('getter', function () {
return {
get: function () {
return {
id: 1,
name: "Test reservation",
status: {
"key": "CANCELED",
"value": "Canceled"
}
};
}
};
}).directive('menu', function () {
return {
restrict: 'E',
scope: {
reservation: '='
},
template: '<ul ng-show="showMenu"><li><a href="#/reservation/{{reservation.id}}">View Reservation</a></li></ul>',
controller: function ($scope) {
if($scope.reservation.status.key == "CANCELED") {
console.log("Canceled");
$scope.showMenu = false;
} else {
console.log("Active");
$scope.showMenu = true;
}
}
};
}).controller('testCtrl', ['$scope', 'getter', function ($scope, getter) {
$scope.reservation = getter.get();
}]);
Fiddle with working code using a local object: http://jsfiddle.net/fedorsmirnoff/jvfaz/3/