Angular Factor Call not working - angularjs

I am trying to call the update / put method in the factory which will in turn save the changes on the form to the database via an API call. But I get a console error below. The update function is getting called from the button click fine, but it doesn't call the factory and API from there. What am I missing? Thank you!
I updated my code with the suggestion below but now have this error:
My console error: "Error: [$injector:unpr] http://errors.angularjs.org/1.2.10/$injector/unpr?p0=%24resourceProvider%20%3C-%20%24resource%20%3C-%20memberUpdate
var securityApp = angular.module('securityApp', ['ngRoute']).
config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'PartialPages/members.html',
controller: 'membersController'
})
.when('/memberDetail/:memberID', {
templateUrl: 'PartialPages/memberDetail.html',
controller: 'memberDetailController'
})
.when('/memberEdit', {
templateUrl: 'PartialPages/memberEdit.html',
controller: 'memberEditController'
});
});
securityApp.factory('memberUpdate', function ($resource) {
return $resource('/api/Members/:id', { id: '#id' }, { update: { method: 'PUT' } });
});
securityApp.controller('memberDetailController', function ($scope, $http, $routeParams, memberUpdate) {
var id = $routeParams.memberID;
$http.get('/api/Members/' + $routeParams.memberID).success(function (data) {
$scope.member = data;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
})
$scope.update = function () {
memberUpdate.update({ id: id }, $scope.member);
};
});

You need to inject memberUpdate into the controller dependencies.
securityApp.controller('memberDetailController', function ($scope, $http, $routeParams, memberUpdate) {
var id = $routeParams.memberID;
$http.get('/api/Members/' + $routeParams.memberID).success(function (data) {
$scope.member = data;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
})
$scope.update = function () { // you don't need to pass $scope and memberUpdate since they are already available into the scope
memberUpdate.update({ id: id }, $scope.member);
};
});

$resource is in a different module so you need to include it.
var securityApp = angular.module('securityApp', ['ngRoute', 'ngResource']).
her how you install it https://docs.angularjs.org/api/ngResource

Related

Controller doesn't see function

This is my services.js
(function () {
var app = angular.module('crmService', []);
app.factory('timeline', ['$http', function ($http) {
var _addTimelineEvent = function (clientId, eventData) {
callback = callback || function () {};
return $http({
method: 'POST',
url: '/simple_crm/web/api.php/client/' + clientId + '/timeline',
data: eventData
});
};
return {
addTimelineEvent: _addTimelineEvent
};
}]);
})();
And this is my controller:
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/clients', {
controller: 'ClientsListCtrl',
templateUrl: 'views/clients-list.html'
})
.when('/clients/:clientId', {
controller: 'ClientDetailCtrl',
templateUrl: 'views/client-details.html'
})
.otherwise({
redirectTo: '/clients'
});
$locationProvider.html5Mode(true).hashPrefix('');
}]);
app.controller('ClientDetailCtrl', ['$scope', 'clients', 'users', 'sectors', '$routeParams', '$timeout', 'timeline',
function ($scope, clients, users, sectors, $routeParams, $timeout, timeline) {
$scope.client = {};
$scope.timeline = [];
$scope.timelineEvent = {};
$scope.eventTypes = timeline.getEventsType();
$scope.saveClientData = function () {
if ($scope.clientForm.$invalid)
return;
clients.updateClient($scope.client.id, $scope.client)
.then(
function () {
//messeges to user
},
function (error) {
console.log(error);
}
);
};
$scope.addEvent = function () {
if ($scope.eventForm.$invalid)
return;
timeline.addTimelineEvent($scope.client.id, $scope.timelineEvent)
.then(
function () {
//messeges to user
},
function (error){
console.log(error);
});
};
}]);
})();
And I get an error:
TypeError timeline.addTimelineEvent is not a function
I am not able to understand why the function that is above works fine but timeline.addTimelineEvent, which is virtually identical, reports an error.
Any advice?
I added all code for better view :
Full code
The timeline function is located at the end of the app file

"$injector:unpr Unknown provider" after adding resolve in $stateProvider

I searched already for similar problems but couldn't figure out what the problem is in my specific case. Maybe one of you has an idea?
My code was executing with out an error but I had to add resolve to my $stateProvider. After doing so I got following error:
Error: [$injector:unpr] Unknown provider: rquoteShipmentListProvider <- rquoteShipmentList <- vendorQuoteCtrl http://errors.angularjs.org/1.4.7/$injector/unpr?p0=rquoteShipmentListProvider%20%3C-%20rquoteShipmentList%20%3C-%20vendorQuoteCtrl at Anonymous function (https://code.angularjs.org/1.4.7/angular.js:4289:13) ...
My code:
var app = angular.module("offerModul", ["ui.router", "ui.bootstrap"]);
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/");
$stateProvider
.state("main",{
url: "/",
controller:'vendorQuoteCtrl',
templateUrl:'src/html/vendorQuoteRequest.html',
resolve: {
rquoteShipmentList: function(shipmentService) {
return shipmentService.loadquoteShipments();
}
}
});
});
app.controller('vendorQuoteCtrl', ['$scope', 'shipmentService', 'carrierService', 'chargesService', 'rquoteShipmentList', function($scope, shipmentService, carrierService, chargesService, rquoteShipmentList) {
$scope.quoteShipmentList = rquoteShipmentList;
$scope.open = function ()
{
init();
}
function init() {
$scope.quoteShipmentList = shipmentService.getquoteShipments();
}
}]);
app.service('shipmentService', ['$http', function ($http) {
var quoteShipmentList = null;
return {
loadquoteShipments: function () {
$http.get("./src/data/getShipments.php",{
cache: true})
.success(function (response) { quoteShipmentList = response; alert("quoteShipmentList:" + quoteShipmentList);})
.error(function (data, status) {
alert("error getting Quotes! status:"+status);
});
alert("should be set:" + quoteShipmentList);
return quoteShipmentList;
},
getquoteShipments: function () {
return quoteShipmentList;
}
};
}]);
Before adding resolve my code is executed without an error. The code before:
var app = angular.module("offerModul", ["ui.router", "ui.bootstrap"]);
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/");
$stateProvider
.state("main",{
url: "/",
controller:'vendorQuoteCtrl',
templateUrl:'src/html/vendorQuoteRequest.html'
});
});
app.controller('vendorQuoteCtrl', ['$scope', 'shipmentService', 'carrierService', 'chargesService', function($scope, shipmentService, carrierService, chargesService) {
$scope.quoteShipmentList = shipmentService.loadquoteShipments();
$scope.open = function ()
{
init();
}
function init() {
$scope.quoteShipmentList = shipmentService.getquoteShipments();
}
}]);
app.service('shipmentService', ['$http', function ($http) {
var quoteShipmentList = null;
var shipmentList = null;
return {
loadquoteShipments: function () {
$http.get("./src/data/getShipments.php",{
cache: true})
.success(function (response) { quoteShipmentList = response; alert("quoteShipmentList:" + quoteShipmentList);})
.error(function (data, status) {
alert("error getting Quotes! status:"+status);
});
alert("should be set:" + quoteShipmentList);
return quoteShipmentList;
},
getquoteShipments: function () {
return quoteShipmentList;
}
};
}]);
Thank you very much for your help!!!
Like recommended in other posts I deleted ng-controller from my html BUT I didn't saw that there was another one in a modal-dialog (?:-/).
Removing that tag removed the error!
Thank you for trying to help!
there is a problem in the resolve. you have to inject your service shipmentService in the resolve like we inject in controller.
Something like :
resolve: {
rquoteShipmentList: ['rquoteShipmentList', function (rquoteShipmentList){
return shipmentService.loadquoteShipments();
}],
}

using factory in angularjs getting Error: [$injector:undef]

I am creating a new angular App and using factory but when i am am getting an error which is
Error: [$injector:undef] http://errors.angularjs.org/1.4.5/$injector/undef?p0=Data
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:6:416
at Object.$get (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:37:32)
at Object.e [as invoke] (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:39:96)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:40:410
at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:38:308)
at e (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:39:64)
at Object.g.instantiate (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:39:213)
at b.$get (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js:80:257)
at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js:12:165)
var app = angular.module('testapp', ['ngRoute']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/userlist', {
title: 'List of all the users',
templateUrl: 'userlist.html',
controller: 'listuser'
})
.when('/profile',{
title:'user detail page',
templateUrl:'profile.html',
controller:'listuser'
})
.otherwise({
redirectTo: '/userlist'
});
}])
app.factory("Data", ['$http','$log',
function ($http,$log) {
var obj = {};
obj.post = function (q, object) {
return $http({
method: 'POST',
url:'userdetail.php',
data: object.user
})
.then(function (results) {
$log.log(results);
return results.data;
});
};
}]);
app.controller('listuser',['Data', function ($scope,$http,$log,$window,Data) {
$scope.userdetail = {};
var init = function () {
$http({
method: 'POST',
url: 'apisource.php',
})
.then(function (results) {
$scope.data=results.data;
});
};
init();
$scope.douserdetail = function(user) {
Data.post({
user: user
}).then(function (results) {
if (results.status == "success") {
//$location.path('dashboard');
}
});
};
}]);
Factory functions in angular are expected to return an object, but your "Data" factory does not return anything. Simply add the following at the end of your factory function to fix the issue:
return obj;
Have a look at the link provided in your stacktrace. Your factory has to return a value:
app.factory("Data", ['$http','$log',
function ($http,$log) {
var obj = {};
...
return obj;
}]);
There are many error, in controller your are using $http, what is the purpose
You are calling init() inside the init which will cause the infinite loop
You service is not returning anything
I will suggest to check the basics angular first

AngularUI Route Resolve Issue when Rejecting Promise

I have included my code below. Basically, when I am loading my view, I am using resolve to get some data. In my service, if my promise is rejected - on error - the resolve gets infinitely called. Is there a better way I should be performing this?
(function () {
function AppService($q, $http, $log, $timeout, pageOptionsModel) {
return {
getPageOptions: function () {
var deferred = $q.defer();
var pageOptions = pageOptionsModel.getPageOptions();
if (pageOptions === null) {
$http.get("api/HomeApi/GetPageOptions")
.success(function (response) {
deferred.resolve(response);
$log.info("Successfully retriedved page options from service.");
})
.error(function (response) {
deferred.reject("Error");
$log.error("Errored while retrieving page options from service.");
});
}
else {
deferred.resolve(pageOptions);
}
return deferred.promise;
}
}
};
function AppConfig($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise("line");
// Now set up the states
$stateProvider
.state('line', {
url: "/line",
templateUrl: "app/line/lineTemplate.html",
controller: "lineController",
controllerAs: "line",
resolve: {
pageOptions: function (appService) {
return appService.getPageOptions();
}
}
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
};
angular.module("app", ["ui.router", "ui.bootstrap", "app.line", "app.modal"])
.config(AppConfig)
.factory("appService", AppService);
})();
Here is my Line Controller which never initializes if my promise is rejected.
(function () {
function LineController($scope, pageOptions) {
var self = this;
// INITIALIZE
self.pageOptions = pageOptions;
};
angular.module("app.line")
.controller("lineController", LineController);
})();

View loads before $scope values are assigned

I've come to this problem were my view loads before $scope params are assigned and this is caused by $http service call taking some time before response is achived.
This leaves me with dropdown boxes being unsync with url params on page reload...
Is there anyway to reload these $scope params or wait til they get values before rendering the view? I would like the easiest solution to this as Im yet farily new to angularjs.
Just give me a hint if more info is needed!
Here's some of the code...
Route
angular.module('app', ['ngRoute', 'app.controller', 'app.service', 'app.filter'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/order/:id', {
templateUrl: '../../App_AngularJs/partials/specificOrder.htm',
controller: 'orderController',
reloadOnSearch: true
})
.when('/orderitem/:id', {
templateUrl: '../../App_AngularJs/partials/orderItem/orderItem.htm',
controller: 'orderItemController',
reloadOnSearch: true
})
.when('/', {
templateUrl: '../../App_AngularJs/partials/searchOrder.htm',
controller: 'ordersController',
reloadOnSearch: false
//Use some resolve here!? How!?
});
}
Controller
var orderContrl = angular.module('app.controller', ['angularTreeview', 'ui.bootstrap'])
.controller('ordersController', [
'$scope', '$routeParams', '$location', '$filter', '$modal', '$log', 'orderService',
function ($scope, $routeParams, $location, $filter, $modal, $log, orderService) {
init();
function init() {
$scope.searchtext = $routeParams.search || '';
$scope.page = $routeParams.page || 1;
$scope.take = $routeParams.take || 10;
$scope.status = $routeParams.status || -1;
$scope.group = $routeParams.group || -1;
$scope.type = $routeParams.type || -1;
$scope.category = $routeParams.category || -1;
$scope.selectedOrganisation = "Knoc LK";
getOrders(true);
getFilters(true);
}
function getFilters(reloadPage) {
orderService.queryOrderAllDropdown()
.then(function (response) {
$scope.orderGroup = response.OrderGroups;
$scope.orderStatus = response.OrderStatus;
$scope.orderType = response.OrderTypes;
$scope.orderPackageCategory = response.ProductPackageCategories;
$scope.orderAllCategory = response.ProductItemCategories;
//Sets type and shows different categories depending on type chosen
getCategory();
//Trying to reassign the values but still nothing...
if (reloadPage) {
angular.forEach($scope.orderStatus, function (value) {
if ($routeParams.status == value.ID)
$scope.status = value.ID;
});
//Trying to reassign the values but still nothing...
$scope.group = $scope.group;
}
},
function (errorMessage) {
$scope.error = errorMessage;
});
}
Service
angular.module('app.service', [])
.service('orderService', ['$http', '$q', function ($http, $q) {
this.queryOrderAllDropdown = function () {
var deferred = $q.defer();
$http({
type: 'GET',
url: 'GenericHandlers/HttpOrderService.ashx',
method: 'GetOrderAllDropdown',
headers: { 'Content-Type': 'text/plain' }
}).success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.reject("An error occured while fetching data");
});
return deferred.promise;
},
You need to use a Resolver to fetch the data from the backend. Adding a "resolve" to the $routeProvider will fetch the data before the controller takes control. Check out this blog post for a similar example.

Resources