[英]Reload directive method after POST in Angular JS
我正在開發一個使用AngularJS作為前端一部分的開源應用程序,由於我希望它工作的方式(這是偏執狂,刪除和添加來自dom的內容以進行保護),我遇到了一個我可以解決的問題似乎無法弄清楚。
網站的主要內容是通過服務加載的,該服務從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 (這是Alpha !,請不要存儲任何對您而言重要的信息,因為數據庫很容易被清除)
源代碼在https://github.com/clione/sikre-frontend/tree/master/assets/js中
我同意,也許整個應用程序的布局都不是最好的,所以歡迎提供糾正它的任何指導。 如果有人對如何使該指令在POST
之后重新加載內容有所了解,將不勝感激。
該解決方案由@Cerad的評論提供。
基本上,我必須創建一個僅由指令捕獲的廣播信號,然后重新加載內容。
在控制器上:
$rootScope.$broadcast('updateItems', $scope.item.category);
關於指令:
$scope.$on('updateItems', function (event, data) {
$scope.getItems(data);
});
getItems是一個調用服務並獲取數據的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.