我有以下代码:
factory
app.factory('Items', function($firebase,FIREBASE_URL) { var ref = new Firebase(FIREBASE_URL); var items = $firebase(ref.child('items')).$asArray(); var Item = { all: function () { return items; }, create: function (item) { return items.$add(item); }, get: function (itemId) { return $firebase(ref.child('items').child(itemId)).$asObject(); }, update: function (itemId, item) { return $firebase(ref.child('items').child(itemId)).update(item); }, delete: function (item) { return items.$remove(item); } }; return Item; });
route
app.config(function($stateProvider) { $stateProvider .state('items_update', { url: '/items/update/:id', templateUrl: 'views/items/form.html', controller:'ItemsUpdateController', resolve:{ item:function(Items,$stateParams){ return Items.get($stateParams.id); } } }) });
controller
app.controller('ItemsUpdateController', function ($scope, item, $state) { $scope.item = item; console.log($scope.item.url); $scope.add = function() { Items.update($scope.item).then(function () { $state.transitionTo('items'); }); } });
为什么console.log($ scope.item.url); 给我不确定的?
但在视图中我拥有所有数据
html
<form class="form-horizontal" role="form" name="form" data-ng-submit="add()"> <div class="form-group"> <input type="text" name="title" tabindex="1" class="form-control" placeholder="{{ 'items.form.title' | translate }}" data-ng-model="item.title" required="required" data-ng-minlength="3" data-ng-maxlength="25" user-feedback /> </div> <div class="form-group"> <input type="text" name="ingredients" tabindex="2" class="form-control" placeholder="{{ 'items.form.ingredients' | translate }}" data-ng-model="item.ingredients" required="required" ng-pattern="/^\w(\s*,?\s*\w)*$/" user-feedback /> </div> <div class="form-group"> <input type="text" name="price" tabindex="3" class="form-control" placeholder="{{ 'items.form.price' | translate }}" data-ng-model="item.price" required="required" data-smart-float user-feedback /> </div> <div class="form-group"> <button type="button" tabindex="4" class="btn btn-default btn-lg" item="item" data-uploader>{{ 'items.form.upload' | translate }}</button> <input type="text" name="url" style="display:none;" required="required" data-ng-model="item.url" /> </div> <div class="form-group form-no-required clearfix"> <div class="pull-right"> <button type="submit" tabindex="5" class="btn btn-primary" data-ng-disabled="form.$invalid">{{ 'items.form.submit' | translate }}</button> </div> </div> </form>
ENDS UP
就像@Frank van Puffelen的评论一样,我的解决方法是:
app.controller('ItemsUpdateController', function($scope, item, $state) { item.$loaded().then(function(data) { $scope.item = data; console.log($scope.item.url); }); $scope.add = function() { Items.update($scope.item).then(function() { $state.transitionTo('items'); }); } });
这是因为在您console.log($scope.item.url);运行时,尚未从Firebase加载数据。Angular侦听Firebase / AngularFire发出的通知,以了解何时加载数据,然后更新视图。
console.log($scope.item.url);
另请参阅angularfire-为什么我不能遍历$ asArray返回的数组?和尝试从Firebase获取子记录。