我正在開發一個開源的應用程序,它使用AngularJS作爲前端的一部分,由於我希望它的工作方式(它是偏執狂,從dom中刪除和添加內容以進行保護)我遇到了一個我似乎無法弄清楚的問題。在Angular JS POST後重新加載指令方法
該網站的主要內容是通過從REST API收集數據並填充指令的服務加載的,該指令調用模板並呈現內容。
的問題是,當你添加新的內容和POST
是成功的,我不能夠告訴指令重新加載的內容,因爲POST
調用來自控制器在不同的$scope
。我試過$watch
,$apply
,$push
,最近我一直在想$resource
,但我不認爲這是解決方案。代碼如下:
指令:
.directive("itemList", function ($timeout) {
return {
restrict: 'A',
template: "<ng-include src='getTemplateUrl()'/>",
replace: true,
controllerAs: 'items',
controller: function ($http, $scope, sikreAPIservice) {
$scope.getItems = function (categoryId) {
sikreAPIservice.getItemsbyCategory(categoryId)
.success(function (data, status) {
$scope.category_name = data.category_name;
$scope.category_id = data.category_id;
$scope.items = data.items;
$scope.lockedItem = false;
$timeout(function() {
$scope.lockedItem = true;
$.notify("View time expired. Locking...", "info");
$scope.getTemplateUrl();
}, itemTimeout);
})
.error(function (data, status) {
$.notify("Couldn't get the item data", "error");
});
};
$scope.getAllItems = function() {
sikreAPIservice.getItems()
.success(function (data) {
$scope.category_name = data.category_name;
$scope.category_id = data.category_id;
$scope.items = data.items;
$scope.lockedItem = false;
$timeout(function() {
$scope.lockedItem = true;
$.notify("View time expired. Locking...", "info");
$scope.getTemplateUrl();
}, itemTimeout);
})
.error(function (data, status) {
$.notify("Couldn't get the item data", "error");
});
};
$scope.getTemplateUrl = function() {
if ($scope.lockedItem) {
return '';
} else {
return 'includes/items.html';
}
$(document).foundation('reflow');
};
},
};
});
服務:
.factory('sikreAPIservice', function ($http) {
//var mainAPIUrl = 'https://api.sikr.io/v1/';
var sikreAPI = {};
sikreAPI.getItemsbyCategory = function (categoryId) {
return $http({
method: "GET",
url: mainAPIUrl + 'items?category=' + categoryId,
cache: false
});
};
});
控制器,做了POST:
.controller('ItemsCtrl', function ($scope, $compile, sikreAPIservice) {
$scope.additem = function (item) {
sikreAPIservice.createItem(item)
.success(function() {
$.notify("Item created", "success");
$scope.item = null;
$('#addItem').foundation('reveal', 'close');
})
.error(function() {
$.notify("Can't save the item", "error");
});
};
});
工作版本位於http://sikr.io/login.html(本是阿爾法,不要存儲任何重要的東西,因爲數據庫將被刪除)
的源代碼是https://github.com/clione/sikre-frontend/tree/master/assets/js
我同意,整個應用程序的可能的佈局是不是最好的,所以任何指導糾正它是值得歡迎的。如果有人想知道如何在POST
之後重新加載內容,我們將不勝感激。
您可能想要在發生更改時進行$ rootScopr。$廣播。這裏是一篇有用的文章:http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribeing/ – Cerad 2015-03-25 13:00:41
@Cerad我會看看它,謝謝! – 2015-03-25 13:29:29
@Cerad不幸的是,它不工作,因爲摘要正在進行,還有其他想法? – 2015-03-26 13:38:09