I think I've a flaw in the design of my AngularJS app.
I have a service which contains one of my model items and the methods associated with adding/deleting them. This service is injected into my core app and also into a directive. My issue is removing items in the model from the directive. I am doing this because the directive physically represents each of the model items. The change is happening, but its not pushing its way back to the core app which exposes the model. I realize that this is because i'm not telling it to update, but my issue is I don't really understand how to. Adding $apply
in the directive after calling the service causes an error that an apply is already in progress, so it feels like this is the wrong approach.
I've put my model in the service as I only want a single instance of this data for the entire app.
Can anyone suggest a better way of achieving this? Is storing the model in the service a good idea?
Service:
angular.module("App").service("widgetService", function () {
this.widgets = [];
this.removeWidget = function() {
<!-- remove item from this.widgets -->
}
this.getWidgets = function() {
return this.widgets;
}
this.setWidgets = function(widgets) {
this.widgets = widgets;
)
}
Core app:
App.controller("CoreAppController", function($scope, $http, widgetService) {
$scope.widgets = widgetService.getWidgets();
}
HTML:
<widget data-ng-repeat="widget in widgets" />
Directive:
myKSS.MyKSSApp.directive("widget", function($compile) {
return {
restrict: "E",
replace: true,
templateUrl: "partials/Widget.html",
scope: {
},
controller: function($scope, $element, $attrs, widgetService) {
$scope.removeWidget = function() {
widgetService.removeWidget();
};
}
}
}