我正在开发一个开源应用程序,它使用 AngularJS 作为前端的一部分,由于我希望它的工作方式(它是偏执的,从 dom 中删除和添加内容以进行保护)我遇到了问题我似乎无法弄清楚。
网站的主要内容通过服务加载,该服务从 REST API 收集数据并填充指令,同一指令调用模板并呈现内容。
问题是,当您添加新内容并且 POST
成功时,我无法告诉指令重新加载内容,因为 POST
调用来了来自不同 $scope
中的 Controller 。我尝试过 $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 :
.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
之后重新加载内容,我们将不胜感激。
最佳答案
此解决方案由@Cerad 的评论提供。
基本上,我必须创建一个仅由指令捕获并重新加载内容的广播信号。
在 Controller 上:
$rootScope.$broadcast('updateItems', $scope.item.category);
关于指令:
$scope.$on('updateItems', function (event, data) {
$scope.getItems(data);
});
getItems 是一个调用服务并获取数据的函数。
关于javascript - Angular JS 中 POST 后重新加载指令方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29255709/