Strange ng-repeat behaviour with local storage - javascript

I am just playing around with ionic and local storage. I am messing with the ionic example app to customise it a bit and I am running into a snag. Basically the home page lists items. Once the user goes into the item they can add to a task list.
To create an item on the home page the user opens a modal and enters info (title,date, etc...) and then stores the items in local storage. The item array has a nested array for the task list.
once the user goes into an item they can open a modal that adds a task. Once submitted the task is pushed to the nested array which works great and outputs:
However, when the user goes back to the home page where all items are listed there are just a number of empty objects repeated (looking in local storage the object is perfect).
My list controller and inner list controller:
.controller('ProfileCtrl', function ($filter, $scope, $stateParams, $timeout, $ionicModal, Eventers) {
var createEventer = function(eventerId, eventerTitle, eventerVenue, eventerDay, eventerMonth, eventerYear, eventerDate) {
var newEventer = Eventers.newEventer(eventerId,eventerTitle, eventerVenue, eventerDay, eventerMonth, eventerYear, eventerDate);
$scope.eventers.push(newEventer);
Eventers.save($scope.eventers);
}
$scope.eventers = Eventers.all();
$ionicModal.fromTemplateUrl('new-event.html', function(modal) {
$scope.eventerModal = modal;
},
{
focusFirstInput: false,
scope: $scope
});
////////////////////////////////
$scope.date = new Date();
console.log($scope.date);
////////////////////////////////
$scope.createEventer = function(eventer, index) {
var eventerId = localStorage.clickcount;
var eventerTitle = eventer.title;
var eventerVenue = eventer.venue;
var eventerDay = eventer.day;
var eventerMonth = eventer.month;
var eventerYear = eventer.year;
var eventerDate = $scope.date;
if (eventerId,eventerTitle, eventerVenue, eventerDay, eventerMonth, eventerYear, eventerDate) {
createEventer(eventerId,eventerTitle, eventerVenue, eventerDay, eventerMonth, eventerYear, eventerDate);
$scope.eventerModal.hide();
eventer.title = "";
eventer.venue = "";
eventer.day = "";
eventer.month = "";
eventer.year = "";
}
console.log(eventer);
};
})
and my inner controller:
.controller('ProfileInnerCtrl', function ($scope, $stateParams,$ionicModal, $timeout, Eventers) {
$scope.eventer = Eventers.get($stateParams.eventerId);
$ionicModal.fromTemplateUrl('new-task.html', function(modal) {
$scope.eventerModal = modal;
},
{
focusFirstInput: false,
scope: $scope
});
$scope.createTask = function(task) {
$scope.eventer.tasks.push({
title: task.title
});
console.log(task.title);
Eventers.save($scope.eventer);
task.title = "";
$scope.eventerModal.hide();
};
$scope.newTask = function() {
$scope.eventerModal.show();
};
$scope.closeNewTask = function() {
$scope.eventerModal.hide();
}
$scope.completionChanged = function() {
Eventers.save($scope.eventers);
};
})
--------EDIT: Add Factory-------
.factory('Eventers', function() {
/**/
return {
all: function() {
var eventerString = window.localStorage['eventers'];
if (eventerString) {
return angular.fromJson(eventerString);
}
return [];
},
save: function(eventers) {
window.localStorage['eventers'] = angular.toJson(eventers);
},
newEventer: function(eventerId, eventerTitle,eventerVenue , eventerDay, eventerMonth, eventerYear, eventerDate) {
return {
id: eventerId,
title: eventerTitle,
venue: eventerVenue,
day: eventerDay,
month: eventerMonth,
year: eventerYear,
date: eventerDate,
tasks: []
};
},
get: function(eventerId){
var hell = window.localStorage['eventers'];
var eventers = JSON.parse(hell);
for (var i = 0; i < eventers.length; i++) {
if (parseInt(eventers[i].id) === parseInt(eventerId)){
console.log(eventerId);
return eventers[i];
}
}
return null;
}
}
});
Added images: the first 2 show the home page and local storage before added a task. the last 2 show local storage after adding task and the home page

Well, when you create a new task you save $scope.eventer in the localStorage, which only has titles in it.
Why not push the whole task object in the $scope.eventer?
$scope.createTask = function(task) {
$scope.eventer.tasks.push(task);
...
EDIT:
Your eventers in localStorage after adding task are not an array, so the ng-repeat takes each key in the object.
try Eventers.save([$scope.eventer]); for test, but you'lll have to rethink the whole proccess, what when you have more than one object in the array? you will lose the old ones this way

Related

$http.put not updating model

I'm attempting to learn the MEAN stack and learning to use the $http service.
I currently have a global check in place that is suppose to update my Sprints model, which looks like:
var SprintSchema = new Schema({
tasks: [{
type: String,
ref: 'Task'
}],
name: {
type: String
},
start: {
type: Date
},
end: {
type: Date
},
active: Boolean
});
The following controller should update the Sprint model when requested, and when I console.log the variable in my success function, it looks like what I would expect it to pass but it doesn't actually end up updating my model. Below is my code and an example of the console.log.
'use strict';
angular.module('inBucktApp')
.service('VariableService', function () {
// AngularJS will instantiate a singleton by calling "new" on this function
var ticketId = 'noTicketYet';
var ticketAssigneeName = 'noTicketNameYet';
return {
getPropertyId: function () {
return ticketId;
},
getPropertyName: function () {
return ticketAssigneeName;
}
,
setProperty: function(value, valueName) {
ticketId = value;
ticketAssigneeName = valueName;
}
};
})
.run(['$rootScope', '$http', 'socket', 'VariableService', function($rootScope, $http, socket, VariableService) {
$rootScope.sprintStart;
$http.get('/api/sprints').success(function(sprints) {
$rootScope.sprints = sprints.pop();
$rootScope.sprintStart = new Date($rootScope.sprints.start);
$rootScope.sprintEnd = new Date($rootScope.sprints.end);
socket.syncUpdates('sprints', $rootScope.sprints);
$http.get('/api/tasks').success(function(task) {
$rootScope.task = task;
$rootScope.taskPop = _.flatten($rootScope.task);
$rootScope.taskPopAgain = $rootScope.task.pop();
socket.syncUpdates('task', $rootScope.task);
$rootScope.updateTicket = function(){
//Goes through the entire array and check each element based on critera.
var taskIdsToAdd = [];
for(var i = 0; i < $rootScope.taskPop.length; i++){
var taskFind = $rootScope.taskPop[i];
//Logic if ticket is not in the sprint
if ((new Date(taskFind.start) >= $rootScope.sprintStart) && (new Date(taskFind.start) <= $rootScope.sprintEnd)){
taskFind.sprint = true;
taskIdsToAdd.push(taskFind._id);
$rootScope.sprints.tasks.push(taskFind._id);
$http.put("/api/tasks/"+taskFind._id,taskFind).success(function(task){
console.log('Logic 1 Ran!');
console.log($rootScope.sprintStart);
// socket.syncUpdates('taskPopAgain', taskFindPopAgain);
});
$http.put("/api/sprints/"+$rootScope.sprints._id,$rootScope.sprints).success(function(sprints){
console.log('Logic 2 Ran!');
console.log($rootScope.sprintStart);
console.log(sprints)
});
console.log($rootScope.sprints);
} else{
console.log('this doesnt work first');
};
//Logic if ticket is not in the sprint
if (new Date(taskFind.start) < $rootScope.sprintStart || new Date(taskFind.start) > $rootScope.sprintEnd){
taskFind.sprint = false;
$http.put("/api/tasks/"+taskFind._id,taskFind).success(function(task){
console.log(task);
});
}else{
console.log('this doesnt work');
};
}
};
$rootScope.updateTicket();
});
});
}]);
Console.Log of console.log(sprints)
Anyone have any idea what I'm doing incorrect here?
Thanks for the help guys.

storing, updating and deleting data from app.controller angularJS

I am struggling with some Javascript that I am currently working on. So I have a simple web application and the following is the AngularJS stuff:
app.filter('startFrom', function () {
return function (input, start) {
if (input) {
start = +start;
return input.slice(start);
}
return [];
};
});
app.controller('MainCtrl', ['$scope', 'filterFilter', function ($scope, filterFilter) {
$scope.items = ["name 1", "name 2", "name 3"
];
$scope.addLink = function () {
$scope.errortext = "";
if (!$scope.newItem) {return;}
if ($scope.items.indexOf($scope.newItem) == -1) {
$scope.items.push($scope.newItem);
$scope.errortext = "submitted";
} else {
$scope.errortext = " in list";
}
};
So I have these and I there is html side of it which displays the list of items. Users have options to add and delete these items from items array.
Question. How do I make sure that when user added or deleted items from the array can still see the edited list after reloading the page? Can someone suggest a way of dealing with it? Would it be possible to store in cookies and after each add/delete action update them, if so how?
thanks
UPDATE:
So I changed the script but it still does not seem to be working.
var app = angular.module('App', ['ui.bootstrap']);
app.filter('startFrom', function () {
return function (input, start) {
if (input) {
start = +start;
return input.slice(start);
}
return [];
};
});
app.factory('ItemsService', ['$window', function ($window) {
var storageKey = 'items',
_sessionStorage = $window.sessionStorage;
return {
// Returns stored items array if available or return undefined
getItems: function () {
var itemsStr = _sessionStorage.getItem(storageKey);
if (itemsStr) {
return angular.fromJson(itemsStr);
}
},
// Adds the given item to the stored array and persists the array to sessionStorage
putItem: function (item) {
var itemsStr = _sessionStorage.getItem(storageKey),
items = [];
if (itemStr) {
items = angular.fromJson(itemsStr);
}
items.push(item);
_sessionStorage.setItem(storageKey, angular.toJson(items));
}
}
}]);
app.controller('MainCtrl', ['$scope', 'filterFilter', 'ItemsService', function ($scope, filterFilter, ItemsService) {
$scope.items = ItemsService.get($scope.items)
$scope.addLink = function () {
$scope.errortext = "";
if (!$scope.newItem) {
return;
}
if ($scope.items.indexOf($scope.newItem) == -1) {
$scope.items.push($scope.newItem);
$scope.errortext = "Submitted";
$scope.items = ItemsService.put($scope.items)
} else {
$scope.errortext = "Link in the list";
}
};
$scope.removeItem = function (item) {
$scope.items.splice($scope.items.indexOf(item), 1);
$scope.items = ItemsService.put($scope.items)
$scope.resetFilters;
};
}]);
Any help how to fix it and how to make sure that if user does not have any items it will use the default $scope.items = ["name 1", "name 2", "name 3"]; ?
You could create a simple get/set service that is using $cookies. It could be like this :
angular.module('myApp')
.factory('ItemsService', ['$cookies', function($cookies) {
var cookieName = 'items'
return {
get: function(defaults) {
return $cookies.get(cookieName).split(',') || defaults
},
put: function(items) {
var expireDate = new Date()
expireDate.setDate(expireDate.getDate() + 1);
$cookies.put(cookieName, items.join(','), { expires: expireDate } )
}
}
}]);
Include ItemsService in your controller and in the main function
$scope.items = ItemsService.get($scope.items)
to get the edited list stored in $cookies (if any), and save the list in addLink() by
ItemsService.put($scope.items)
I would like to extend #davidkonrad's answer here, by making his service to use sessionStorage. Since using sessionStorage is most suited for your usecase.
angular.module('myApp')
.factory('ItemsService', ['$window', function($window) {
var storageKey = 'items',
_sessionStorage = $window.sessionStorage;
return {
// Returns stored items array if available or return undefined
getItems: function() {
var itemsStr = _sessionStorage.getItem(storageKey);
if(itemsStr) {
return angular.fromJson(itemsStr);
}
return ['name1', 'name2', 'name3']; // return default value when there is nothing stored in sessionStore
},
// Adds the given item to the stored array and persists the array to sessionStorage
putItem: function(item) {
var itemsStr = _sessionStorage.getItem(storageKey),
items = [];
if(itemStr) {
items = angular.fromJson(itemsStr);
}
items.push(item);
_sessionStorage.setItem(storageKey, angular.toJson(items));
}
}
}]);

Clearing a page and reloading a controller?

So I have a small angular app that takes in a search query, sends it to an elasticsearch node I've got set up, and then displays the result set on screen.
My problem is that when I make a new query, the results gets appended to the end of the current result set. What I would like it to do is to erase whatever is currently on the page, and reload it with only the new data, much like how searching for something on Google returns a completely new set of results.
Is there any way to do this? Code below for reference.
// this is the controller that displays the reuslts.
var displayController = function($scope, $rootScope, $window, notifyingService) {
var dataReady = function(event, data) {
$scope.resultSet = notifyingService.getData();
}
$rootScope.$on('data-ready', dataReady)
}
app.controller("displayController", ["$scope", "$rootScope", "$window", "notifyingService", displayController]);
// this is the service that's responsible for setting the data
var notifyingService = function($http, $rootScope) {
var svc = {
_data: [],
setData: setData,
getData: getData
};
function getData() {
return svc._data;
}
function setData(data) {
var base_obj = data.hits.hits
console.log("Setting data to passed in data.");
console.log('length of dataset: ' + base_obj.length);
for(var i = 0; i < base_obj.length; i++){
svc._data.push(base_obj[i]._source);
}
$rootScope.$broadcast('data-ready', svc._data);
}
return svc;
};
app.factory("notifyingService", ["$http", "$rootScope", notifyingService]);
In setData just before the loop re-initialize svc._data
svc._data = [];
Clear you svc._data before you start adding the new query.
function setData(data) {
var base_obj = data.hits.hits;
svc._data = [];//reset your array before you populate it again.
for(var i = 0; i < base_obj.length; i++){
svc._data.push(base_obj[i]._source);
}
$rootScope.$broadcast('data-ready', svc._data);
}

AngularJS : factory to return data from a php service using $http

I'm newbie to js and this is my first question in stackoverflow as well. So any comment or act of downgrading is understandable.
This is the angular-js-flowchart project on github.
This is another stackoverflow topic that teachs how to use factory as a data getter involving $http.
My need is to generate data for the chart by using an Angular factory that returns a $http function. The $http talks to a php service that retrieve data from database. I have tested the service using jsonlint and its working fine. The directory of service is checked, relatively to the html file.
I copied the "factory" code from another stackoverflow question and applied to app.js in the angularjs-flowchart Github project.
The problem is that the Chrome console keeps throwing an error that I can not understand. Data is not retrieved. The error on console is "TypeError: Cannot read property 'getData' of undefined"
This is the modified-by-me app.js:
//
// Define the 'app' module.
//
angular.module('app', ['flowChart', ])
//
// Simple service to create a prompt.
//
.factory('prompt', function () {
/* Uncomment the following to test that the prompt service is working as expected.
return function () {
return "Test!";
}
*/
// Return the browsers prompt function.
return prompt;
})
//
// Application controller.
//
.controller('AppCtrl', ['$scope', 'prompt', function AppCtrl ($scope, prompt, dataFactory) {
//
// Code for the delete key.
//
var deleteKeyCode = 46;
//
// Code for control key.
//
var ctrlKeyCode = 65;
//
// Set to true when the ctrl key is down.
//
var ctrlDown = false;
//
// Code for A key.
//
var aKeyCode = 17;
//
// Code for esc key.
//
var escKeyCode = 27;
//
// Selects the next node id.
//
var nextNodeID = 10;
//
// Event handler for key-down on the flowchart.
//
$scope.keyDown = function (evt) {
if (evt.keyCode === ctrlKeyCode) {
ctrlDown = true;
evt.stopPropagation();
evt.preventDefault();
}
};
//
// Event handler for key-up on the flowchart.
//
$scope.keyUp = function (evt) {
if (evt.keyCode === deleteKeyCode) {
//
// Delete key.
//
$scope.chartViewModel.deleteSelected();
}
if (evt.keyCode == aKeyCode && ctrlDown) {
//
// Ctrl + A
//
$scope.chartViewModel.selectAll();
}
if (evt.keyCode == escKeyCode) {
// Escape.
$scope.chartViewModel.deselectAll();
}
if (evt.keyCode === ctrlKeyCode) {
ctrlDown = false;
evt.stopPropagation();
evt.preventDefault();
}
};
//
// Add a new node to the chart.
//
$scope.addNewNode = function () {
var nodeName = prompt("Enter a task name:", "New Task");
if (!nodeName) {
return;
}
//
// Template for a new node.
//
var newNodeDataModel = {
name: nodeName,
id: nextNodeID++,
x: 0,
y: 0,
inputConnectors: [
{
name: "Pre"
}
],
outputConnectors: [
{
name: "Sub"
}
],
};
$scope.chartViewModel.addNode(newNodeDataModel);
};
//
// Add an input connector to selected nodes.
//
$scope.addNewInputConnector = function () {
var connectorName = prompt("Enter a connector name:", "New connector");
if (!connectorName) {
return;
}
var selectedNodes = $scope.chartViewModel.getSelectedNodes();
for (var i = 0; i < selectedNodes.length; ++i) {
var node = selectedNodes[i];
node.addInputConnector({
name: connectorName,
});
}
};
//
// Add an output connector to selected nodes.
//
$scope.addNewOutputConnector = function () {
var connectorName = prompt("Enter a connector name:", "New connector");
if (!connectorName) {
return;
}
var selectedNodes = $scope.chartViewModel.getSelectedNodes();
for (var i = 0; i < selectedNodes.length; ++i) {
var node = selectedNodes[i];
node.addOutputConnector({
name: connectorName,
});
}
};
//
// Delete selected nodes and connections.
//
$scope.deleteSelected = function () {
$scope.chartViewModel.deleteSelected();
};
//
// Setup the data-model for the chart.
//
var chartDataModel = {};
var handleSuccess = function(data, status){
chartDataModel = data;
console.log(chartDataModel);
};
dataFactory.getData().success(handleSuccess);
//
// Create the view-model for the chart and attach to the scope.
//
$scope.chartViewModel = new flowchart.ChartViewModel(chartDataModel);
}])
.factory('dataFactory', function($http){
return {
getData : function(){
return $http.post("chart-data-retrieve.php");
}
};
});
Basically, what i added but doesn't work is
// Setup the data-model for the chart.
//
var chartDataModel = {};
var handleSuccess = function(data, status){
chartDataModel = data;
console.log(chartDataModel);
};
dataFactory.getData().success(handleSuccess);
and
.factory('dataFactory', function($http){
return {
getData : function(){
return $http.post("chart-data-retrieve.php");
}
};
});
Please help, thanks.
I tried to set the chartViewModel of the $scope directly inside the service call, so the variable chartDataModel becomes redundant. And it works.
// Create the view-model for the chart and attach to the scope.
//
myService.then(function(data) {
$scope.chartViewModel = new flowchart.ChartViewModel(data);
});
I tried to return a promise, not a $http from the factory. It works now. The controller can now use the service to retrieve data. However I still could not set the controller's variable to the data retrieved.
The following is the code:
.factory('myService', function($http, $q) {
//this runs the first time the service is injected
//this creates the service
var deferred = $q.defer();
$http.get('chart-data-retrieve.php').then(function(resp) {
deferred.resolve(resp.data);
});
return deferred.promise;
})
And the code inside controller:
var chartDataModel = {};
//get data from myService factory
myService.then(function(data) {
alert(data);
chartDataModel = data;
});
Currently, the alert() show me the data already. However, the variable chartDataModel is still unset.

Angularjs must refresh page to see changes

What I have is simple CRUD operation. Items are listed on page, when user clicks button add, modal pops up, user enters data, and data is saved and should automatically (without refresh)be added to the list on page.
Service:
getAllIncluding: function(controllerAction, including) {
var query = breeze.EntityQuery.from(controllerAction).expand(including);
return manager.executeQuery(query).fail(getFailed);
},
addExerciseAndCategories: function(data, initialValues) {
var addedExercise = manager.createEntity("Exercise", initialValues);
_.forEach(data, function(item) {
manager.createEntity("ExerciseAndCategory", { ExerciseId: addedExercise._backingStore.ExerciseId, CategoryId: item.CategoryId });
});
saveChanges().fail(addFailed);
function addFailed() {
removeItem(items, item);
}
},
Controller:
$scope.getAllExercisesAndCategories = function() {
adminCrudService.getAllIncluding("ExercisesAndCategories", "Exercise,ExerciseCategory")
.then(querySucceeded)
.fail(queryFailed);
};
function querySucceeded(data) {
$scope.queryItems = adminCrudService.querySucceeded(data);
var exerciseIds = _($scope.queryItems).pluck('ExerciseId').uniq().valueOf();
$scope.exerciseAndCategories = [];
var createItem = function (id, exercise) {
return {
ExerciseId: id,
Exercise : exercise,
ExerciseCategories: []
};
};
// cycle through ids
_.forEach(exerciseIds, function (id) {
// get all the queryItems that match
var temp = _.where($scope.queryItems, {
'ExerciseId': id
});
// go to the next if nothing was found.
if (!temp.length) return;
// create a new (clean) item
var newItem = createItem(temp[0].ExerciseId, temp[0].Exercise);
// loop through the queryItems that matched
_.forEach(temp, function (i) {
// if the category has not been added , add it.
if (_.indexOf(newItem.ExerciseCategories, i.ExerciseCategory) < 0) {
newItem.ExerciseCategories.push(i.ExerciseCategory);
}
});
// Add the item to the collection
$scope.items.push(newItem);
});
$scope.$apply();
}
Here is how I add new data from controller:
adminCrudService.addExerciseAndCategories($scope.selectedCategories, { Name: $scope.NewName, Description: $scope.NewDesc });
So my question is, why list isn't updated in real time (when I hit save I must refresh page).
EDIT
Here is my querySuceeded
querySucceeded: function (data) {
items = [];
data.results.forEach(function(item) {
items.push(item);
});
return items;
}
EDIT 2
I believe I've narrowed my problem !
So PW Kad lost two hours with me trying to help me to fix this thing (ad I thank him very very very much for that), but unfortunately with no success. We mostly tried to fix my service, so when I returned to my PC, I've again tried to fix it. I believe my service is fine. (I've made some changes as Kad suggested in his answer).
I believe problem is in controller, I've logged $scope.items, and when I add new item they don't change, after that I've logged $scope.queryItems, and I've noticed that they change after adding new item (without refresh ofc.). So probably problem will be solved by somehow $watching $scope.queryItems after loading initial data, but at the moment I'm not quite sure how to do this.
Alright, I am going to post an answer that should guide you on how to tackle your issue. The issue does not appear to be with Breeze, nor with Angular, but the manner in which you have married the two up. I say this because it is important to understand what you are doing in order to understand the debug process.
Creating an entity adds it to the cache with an entityState of isAdded - that is a true statement, don't think otherwise.
Now for your code...
You don't have to chain your query execution with a promise, but in your case you are returning the data to your controller, and then passing it right back into some function in your service, which wasn't listed in your question. I added a function to replicate what yours probably looks like.
getAllIncluding: function(controllerAction, including) {
var query = breeze.EntityQuery.from(controllerAction).expand(including);
return manager.executeQuery(query).then(querySucceeded).fail(getFailed);
function querySucceeded(data) {
return data.results;
}
},
Now in your controller simply handle the results -
$scope.getAllExercisesAndCategories = function() {
adminCrudService.getAllIncluding("ExercisesAndCategories", "Exercise,ExerciseCategory")
.then(querySucceeded)
.fail(queryFailed);
};
function querySucceeded(data) {
// Set your object directly to the data.results, because that is what we are returning from the service
$scope.queryItems = data;
$scope.exerciseAndCategories = [];
Last, let's add the properties we create the entity and see if that gives Angular a chance to bind up properly -
_.forEach(data, function(item) {
var e = manager.createEntity("ExerciseAndCategory");
e.Exercise = addedExercise; e.Category: item.Category;
});
So I've managed to solve my problem ! Not sure if this is right solution but it works now.
I've moved everything to my service, which now looks like this:
function addCategoriesToExercise(tempdata) {
var dataToReturn = [];
var exerciseIds = _(tempdata).pluck('ExerciseId').uniq().valueOf();
var createItem = function (id, exercise) {
return {
ExerciseId: id,
Exercise: exercise,
ExerciseCategories: []
};
};
// cycle through ids
_.forEach(exerciseIds, function (id) {
// get all the queryItems that match
var temp = _.where(tempdata, {
'ExerciseId': id
});
// go to the next if nothing was found.
if (!temp.length) return;
// create a new (clean) item
var newItem = createItem(temp[0].ExerciseId, temp[0].Exercise);
// loop through the queryItems that matched
_.forEach(temp, function (i) {
// if the category has not been added , add it.
if (_.indexOf(newItem.ExerciseCategories, i.ExerciseCategory) < 0) {
newItem.ExerciseCategories.push(i.ExerciseCategory);
}
});
// Add the item to the collection
dataToReturn.push(newItem);
});
return dataToReturn;
}
addExerciseAndCategories: function (data, initialValues) {
newItems = [];
var addedExercise = manager.createEntity("Exercise", initialValues);
_.forEach(data, function (item) {
var entity = manager.createEntity("ExerciseAndCategory", { ExerciseId: addedExercise._backingStore.ExerciseId, CategoryId: item.CategoryId });
items.push(entity);
newItems.push(entity);
});
saveChanges().fail(addFailed);
var itemsToAdd = addCategoriesToExercise(newItems);
_.forEach(itemsToAdd, function (item) {
exerciseAndCategories.push(item);
});
function addFailed() {
removeItem(items, item);
}
}
getAllExercisesAndCategories: function () {
var query = breeze.EntityQuery.from("ExercisesAndCategories").expand("Exercise,ExerciseCategory");
return manager.executeQuery(query).then(getSuceeded).fail(getFailed);
},
function getSuceeded(data) {
items = [];
data.results.forEach(function (item) {
items.push(item);
});
exerciseAndCategories = addCategoriesToExercise(items);
return exerciseAndCategories;
}
And in controller I have only this:
$scope.getAllExercisesAndCategories = function () {
adminExerciseService.getAllExercisesAndCategories()
.then(querySucceeded)
.fail(queryFailed);
};
function querySucceeded(data) {
$scope.items = data;
$scope.$apply();
}

Categories