Why Unknown function "getJalse" in factory Angular JS - angularjs

I am trying make an ajax request to php from angular js. But I am not getting the data I have sent by php file.
an error Unknown function "getJalse" exist in factory
My source:
File app.js:
(function () {
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'contentsCtrl',
templateUrl: 'views/contents.php'
})
.when('/jalse/:jalseId', {
controller: 'recordsCtrl',
templateUrl: 'views/jalse.php'
})
.otherwise({redirectTo: '/'});
});
}());
File jalseFactory.js:
(function () {
'use strict';
var jasleFactory = function ($http, $q) {
var factory = {};
factory.getJalses = function () {
var deferred = $q.defer();
$http({method: 'GET', url: 'includes/records.php'}).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
return factory;
};
jasleFactory.$inject = ['$http', '$q'];
angular.module('myApp').factory('jasleFactory', jasleFactory);
}());
File recordsCtrl.js:
(function () {
'use strict';
var recordsCtrl = function ($scope, $routeParams , jasleFactory) {
var jalseId = $routeParams.jalseId;
$scope.records = jasleFactory.getJalse();
$scope.jalse = null;
function init() {
for (var i = 0, len = $scope.records.length; i < len; i++) {
if ($scope.records[i].contentID == parseInt(jalseId)) {
$scope.jalse = $scope.records[i];
break;
}
}
}
init();
};
recordsCtrl.$inject = ['$scope' , '$routeParams' , 'jasleFactory'];
angular.module('myApp').controller('recordsCtrl', recordsCtrl);
}());

Because your factory has getJalses and you are calling getJalse.
Change
factory.getJalses = function ()
To
factory.getJalse = function ()

Related

Store data from controller to service in angularjs

Although there are many questions regarding the subject , yet I am unable to figure it out , how to proceed further.
I am new in AngularJS. I want to pass data coming from API in Controller and pass it to another function. For this I know I have to create a Service. But after coming to this extend of code I am unable to figure it, how to store it in Service and pass it on other Controller or of function within same Controller. I am new in making Service.
Controller:
$scope.GetR = function (){
$scope.X = null;
$scope.Y = null;
$http({method: 'POST', url: 'http://44.43.3.3/api/infotwo',
headers: {"Content-Type": "application/json"},
data: $scope.ResponseJson
})
.success(function(data, status, headers, config) {
$scope.X = data.X;
$scope.Y = data.Y;
//console.log($scope.X+"and"+$scope.Y);
//Seding RS to API to get AAs
$scope.RJson = {
"ICl": $scope.ICl,
"RS": $scope.X
};
$http({method: 'POST', url: 'http://44.128.44.5/api/apithree',
headers: {"Content-Type": "application/json"},
data: $scope.RJson
})
.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:"+$scope.Eq+" FIn:"+$scope.FIn+" MM:"+$scope.MM);
}).error(function(data, status, headers, config) {
console.log("API failed...");
});
}).error(function(data, status, headers, config) {
console.log("Something went wrong...");
});
};
Now I want to pass this data to Service so that I can call this output on other API input
.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:"+$scope.Eq+" FIn:"+$scope.FIn+" MM:"+$scope.MM);
This shows how to create a service and share data between two controllers.
The service:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.service('MyService', MyService);
MyService.$inject = [];
function MyService() {
this.data = null;
}
})();
First controller:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.controller('MyFirstController', MyFirstController);
MyFirstController.$inject = ['MyService', '$http'];
function MyFirstController(MyService, $http) {
var vm = this;
vm.data = MyService.data;
$http.post('/someUrl', whatEverData).then(resp=> {
MyService.data = resp.data;
})
}
})();
Second controller:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.controller('MySecondController', MySecondController);
MySecondController.$inject = ['MyService', '$http'];
function MySecondController(MyService, $http) {
var vm = this;
vm.data = MyService.data; // Here you can use the same data
}
})();
Not sure if this is what you are looking for. Below code is not tested (May have syntax errors)
Service:
function() {
'use strict';
angular
.module('myAppName')
.factory('MyService', MyService);
MyService.$inject = [];
function MyService() {
var data = null;
return {
getData: function() {
return data;
},
setData: function(d) {
data = d;
}
}
}
})();
Controller:
(function() {
'use strict';
angular
.module('myAppName')
.factory('controller', controller);
controller.$inject = ['$scope', '$http', 'MyService'];
function controller($scope, $http, MyService) {
$scope.GetR = function() {
$scope.X = null;
$scope.Y = null;
var promise = $http({
method: 'POST',
url: 'http://44.43.3.3/api/infotwo',
headers: {
"Content-Type": "application/json"
},
data: $scope.ResponseJson
});
promise.success(function(data, status, headers, config) {
$scope.X = data.X;
$scope.Y = data.Y;
//console.log($scope.X+"and"+$scope.Y);
//Seding RS to API to get AAs
$scope.RJson = {
"ICl": $scope.ICl,
"RS": $scope.X
};
}).error(function(data, status, headers, config) {
console.log("Something went wrong...");
});
return promise;
};
$scope.sendRS = function() {
var promise = $http({
method: 'POST',
url: 'http://44.128.44.5/api/apithree',
headers: {
"Content-Type": "application/json"
},
data: $scope.RJson
});
promise.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:" + $scope.Eq + " FIn:" + $scope.FIn + " MM:" + $scope.MM);
}).error(function(data, status, headers, config) {
console.log("API failed...");
});
return promise;
}
var init = function() {
$scope.GetR().then(function() {
$scope.sendRS().then(function(data) {
MyService.setData({
At: data,
Eq: data.AA.Eq,
FIn: data.AA.FIn,
MM: data.AA.MM
});
})
})
}
init();
}
})();
Other controller
(function() {
'use strict';
angular
.module('myAppName')
.controller('controller1', controller1);
controller1.$inject = ['$scope', 'MyService'];
function controller1($scope, MyService) {
$scope.data = MyService.getData();
}
})();

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

Error: $injector:modulerr Module Error in my browser

I'm new to AngularJS and I'm trying to run this AngularJS that should modify the URL without reloading the page but the console says Uncaught Error: [$injector:modulerr]
Where is the problem?
var app = angular.module("SearchAPP", ['ng-route']);
app.run(['$route', '$rootScope', '$location',
function($route, $rootScope, $location) {
var original = $location.path;
$location.path = function(path, reload) {
if (reload === false) {
var lastRoute = $route.current;
var un = $rootScope.$on('$locationChangeSuccess', function() {
$route.current = lastRoute;
un();
});
}
return original.apply($location, [path]);
};
}
]);
app.controller('GetController', ['$http', '$scope', '$location',
function($http, $scope, $rootScope, $location) {
$scope.click = function() {
var response = $http({
url: 'http://localhost:4567/search',
method: "GET",
params: {
keyword: $scope.searchKeyword
}
});
response.success(function(data, status, headers, config) {
$scope.searchResults1 = data;
// $http.defaults.useXDomain = true;
$location.path('/' + $scope.searchKeyword, false);
});
response.error(function(data, status, headers, config) {
alert("Error.");
});
};
}
]);
Attach angualar-route.js and use ngRoute instead of ng-route
var app = angular.module("SearchAPP", ['ngRoute']);

Angular.js Consuming Upload.progress event in a controller

I have a code that uploads documents in the controller, I wanted it to be moved to a service, so that other controllers can consume it.
"use strict";
angular.module('myApp')
.service('uploadDocumentService', ['Upload', function (Upload) {
this.UploadDocument = function ($file, data) {
Upload.upload({
url: '/uploadDocuments',
file: $file,
data: data
}).progress(function (evt) {
var progressReport = {};
progressReport.progressVisible = true;
progressReport.percentage = Math.round(evt.loaded / evt.total * 100);
return progressReport;
}).success(function (data, status, headers, config) {
var fileUploaded = {};
fileUploaded.id = data.id;
fileUploaded.name = data.fileName;
return fileUploaded;
});
}
}]);
I am unable to capture the .progress event in my controller
uploadDocumentService.UploadDocument($file, 'Path')
.progress(function (progressReport) {
//Some code
}).success(function (data) {
//Some code
});
Keep getting the error Cannot read property 'progress' of undefined
at m.$scope.uploadDocuments
Any tips on how to solve this problem, do I need to register the progress event in the service?
Controller code
"use strict";
angular.module('myApp')
.controller('controller', ['$scope', '$http', 'Upload', 'uploadDocumentService', function ($scope, $http, Upload, uploadDocumentService) {
$scope.uploadDocuments = function ($files) {
$scope.progressVisible = false;
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
uploadDocumentService.UploadDocument($file, 'path')
.progress(function (evt) {
$scope.progressVisible = true;
$scope.percentage = Math.round(evt.loaded / evt.total * 100);
}).success(function (data) {
var fileUploaded = {};
fileUploaded.id = data.id;
fileUploaded.name = data.fileName;
$scope.filesUploaded.push(fileUploaded);
$scope.isFileUploaded = true;
});
}]);
A colleague pointed out the mistake, the fix is as below, return was missing in the statement Upload.upload
"use strict";
angular.module('myApp')
.service('uploadDocumentService', ['Upload', function (Upload) {
this.UploadDocument = function ($file, data) {
return Upload.upload({
url: '/uploadDocuments',
file: $file,
data: data
}).progress(function (evt) {
}).success(function (data, status, headers, config) {
});
}
}]);
To achieve your expected result,add uploadDocumentService param in your controller function.
angular.module('myApp').controller("controller", function($scope, uploadDocumentService)

Angularjs $on not firing after $rootScope.$broadcast

I have this code where two controllers are using a shared service to communicate.
var app = angular.module('AdminApp', ['ngRoute']);
app.factory('SharedService', function ($rootScope) {
var sharedService = {
userId: [],
BroadcastUserId: function (id) {
this.userId.push(id);
$rootScope.$broadcast('handleBroadcast');
}
};
return sharedService;
});
app.config(function ($routeProvider) {
$routeProvider.when('/login', {
templateUrl: "adminLogin.html"
});
$routeProvider.when('/main', {
templateUrl: 'adminMain.html'
});
$routeProvider.otherwise({
redirectTo: '/login'
});
});
app.controller('authCtrl', function ($scope, $http, $location, SharedService) {
$scope.Userid = '';
$scope.authenticate = function (user, pass) {
$http.post('http://localhost/NancyAPI/auth', {
UserName: user,
Password: pass
}).success(function (data) {
$scope.$broadcast('Token', data.Token);
$http.defaults.headers.common['Authorization'] = 'Token ' + data.Token;
$scope.Userid = data.UserId;
SharedService.BroadcastUserId($scope.Userid);
$location.path("/main");
}).error(function (response) {
$scope.authenticationError = response.error || response;
});
};
$scope.$on('handleBroadcast', function () {
console.log('on');
});
}).$inject = ['$scope', '$rootScope', 'SharedService'];
app.controller('mainCtrl', function ($scope, $http, $q, SharedService) {
$scope.tests = [];
$scope.userId = -1;
$scope.getTests = function () {
var deferred = $q.defer();
$http.get('http://localhost/NancyAPI/auth/tests/' + $scope.userId).
success(function (data) {
deferred.resolve(data);
$scope.tests = angular.fromJson(data);
}).error(function (response) {
});
};
// THIS IS NOT FIRING
$scope.$on('handleBroadcast', function () {
$scope.userId = SharedService.userId;
});
}).$inject = ['$scope', '$rootScope', 'SharedService'];
For some reason the $scope.$on is firing in the AuthCtrl controller but not in the mainCtrl.
// THIS IS NOT FIRING
$scope.$on('handleBroadcast', function () {
$scope.userId = SharedService.userId;
});
Why is this happening and how do I fix it?
I made a subtle mistake of not providing the {$rootScope} as dependency. Once I corrected that, it worked for me. I used Inline Array Annotation mechanism to achieve the same.

Resources