我将对象绑定到指令的范围,并根据对象的status属性值,指令将显示或隐藏菜单。
如果在将对象传递给指令之前创建并可用于控制器,则一切正常。但是,当我更改代码以从服务器检索此对象时,条件语句无法声明属性状态未定义。
使用服务中包含的资源在我的控制器中检索远程对象:
var reservation = Reservation.get({id: $routeParams.id}, function(){
$scope.reservation = reservation;
});
服务看起来像这样:
services.factory('Reservation', ['$resource', 'AppSettings', '$log',
function($resource, AppSettings, $log){
return $resource(AppSettings.serverUrl + '/reservations/:id', {}, {
update: {method:'PUT', params: {id: '@id'}}
});
}
]);
我几乎肯定会发生这种情况,因为指令在通过资源检索对象之前加载。有没有办法在加载对象后执行指令的控制器?下面是我使用本地创建的对象的简化工作代码。
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();
}]);
使用本地对象摆弄工作代码:http://jsfiddle.net/fedorsmirnoff/jvfaz/3/