angular.module('cmfApp').controller('InventoryAddCtrl', ['$scope', '$http', '$timeout', function($scope, $http, $timeout){
$scope.submit = function() {
var postData = {
ihenterprise_logisticsbundle_stockItem: {
name: $scope.formData.name,
itemNo: $scope.formData.itemNo
}
}
$http({
method : 'POST',
url : Routing.generate('ih_enterprise_api_stock_item_new'),
data : $.param(postData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
$scope.stockItems = $scope.stockItems.concat(data);
//console.log($scope.stockItems); This logs with the new item
}).error(function(error) {
console.log(error);
});
};
}]);
如果我尝试调用$ scope,那么当我连接到scope数组时,视图根本就不会更新。$ apply();在concat之后,我得到了正在进行的摘要,我也尝试过使用setTimeout,但没有帮助。
这是html(Twig):
{% block listTable %}
<table class="table table-condensed table-expanding">
<thead>
<tr>
<th> </th>
<th>Id</th>
<th>Created At</th>
<th>Navn</th>
</tr>
</thead>
<tbody>
<tr ng-repeat-start="stockItem in stockItems" data-toggle="collapse" data-target="#stockItem_{{ '{{stockItem.id}} '}}" class="accordion-toggle">
<td>
<button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button>
</td>
<td>{{ '{{stockItem.id}} '}}</td>
<td>{{ '{{stockItem.created_at}} '}}</td>
<td>{{ '{{stockItem.name}} '}}</td>
</tr>
<tr ng-repeat-end="">
<td colspan="6" class="hiddenRow">
<div class="accordian-body collapse" id="package_{{ '{{stockItem.id}} '}}">
test
</div>
</td>
</tr>
</tbody>
</table>
{% endblock %}
控制器InventoryAddCtrl位于块之外,初始数据在页面刷新时正确应用。
答案 0 :(得分:0)
angular.module('cmfApp').controller('InventoryAddCtrl', ['$scope', '$http', '$timeout', function($scope, $http, $timeout){
$scope.submit = function() {
var postData = {
ihenterprise_logisticsbundle_stockItem: {
name: $scope.formData.name,
itemNo: $scope.formData.itemNo
}
}
$http({
method : 'POST',
url : Routing.generate('ih_enterprise_api_stock_item_new'),
data : $.param(postData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
//You need to use $apply here.
$timeout(function(){
$scope.$apply(function(){
$scope.stockItems = $scope.stockItems.concat(data);
});
});
//console.log($scope.stockItems); This logs with the new item
}).error(function(error) {
console.log(error);
});
};
}]);
答案 1 :(得分:-1)
我不确定,但我认为你没有将$scope.stockItems
定义为空数组。
只需将$scope.stockItems=[];
放在$scope.submit()
函数