Error: $injector:modulerr Module Error in my browser - angularjs

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']);

Related

object doesn't support property or method getUserData

LoginController.js
var MyApp = angular.module('MyApp', []);
MyApp.controller("LoginController",
["$scope", "$rootScope",
function ($scope , dataService) {
$scope.user = "sample";
$scope.checkUser = function () {
dataService.getUserData($scope.user).then(
function (results) {
$scope.userLoginInfo = results.userInfo;
},
function (results) {
$rootScope.showAlert(results, "There is a problem when trying to get user details.");
});
};
}]);
My DataService.js
MyApp.factory("dataService",
["$http", "$rootScope", "$q",
function ($http, $rootScope,$q) {
var dataService = {};
var getUserData = function (username) {
var promise = $http.get(baseUrl()+"/Controllers/UserDetails/?username=" + username)
.success(function (data, status, headers, config) {
return data;
})
.error(function (data, status, headers, config) {
return data;
});
return promise;
}
return {
getUserData: getUserData
}
}]);
i have included all .js files via bundleconfig .on calling dataService.getUserData in login controller , the described error occurs.
following is the stack trace
"TypeError: Object doesn't support property or method 'getUserData'\n at $scope.checkUser (http://localhost:58949/app/Controllers/LoginController.js:41:9)
at fn (Function code:2:195)\n at expensiveCheckFn (http://localhost:58949/Scripts/angular.js:16123:11)\n at callback (http://localhost:58949/Scripts/angular.js:26490:17)\n at Scope.prototype.$eval (http://localhost:58949/Scripts/angular.js:17913:9)\n at Scope.prototype.$apply (http://localhost:58949/Scripts/angular.js:18013:13)\n at Anonymous function (http://localhost:58949/Scripts/angular.js:26495:17)\n at n.event.dispatch (http://localhost:58949/Scripts/jquery-2.2.3.min.js:3:7481)\n at r.handle (http://localhost:58949/Scripts/jquery-2.2.3.min.js:3:5547)"
any help is greatly appreciated
You have not injected dataService so in your scenario instead of accessing "dataService" it is accesing "$rootScope"
try this :
// controller
var MyApp = angular.module('MyApp', []);
MyApp.controller("LoginController", ["$scope", "$rootScope", "dataService",
function($scope, $rootScope, dataService) {
$scope.user = "sample";
$scope.checkUser = function() {
dataService.getUserData($scope.user).then(
function(results) {
$scope.userLoginInfo = results.userInfo;
},
function(results) {
$rootScope.showAlert(results, "There is a problem when trying to get user details.");
});
};
}
]);
Also in your service
following line /Controllers/UserDetails/?username= seems to be incorrect, We pass query parameter in following way :
// "/Controllers/UserDetails?username="
// Service
MyApp.factory("dataService", ["$http", "$rootScope", "$q",
function($http, $rootScope, $q) {
var dataService = {};
var getUserData = function(username) {
var promise = $http.get(baseUrl() + "/Controllers/UserDetails?username=" + username)
.success(function(data, status, headers, config) {
return data;
})
.error(function(data, status, headers, config) {
return data;
});
return promise;
}
return {
getUserData: getUserData
}
}
]);
Inject the dataService.
MyApp.controller("LoginController",
["$scope", "$rootScope","dataService",
function ($scope ,rootScope dataService) {
. .
}
If the dataService not injected properly, hence it throws the error.

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)

Why Unknown function "getJalse" in factory Angular JS

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 ()

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.

getting an err like: Uncaught Error: [$injector:modulerr]

Am new to angular js....i wrote simple example using http post call..
but it throws an error like
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.3/$injector/modulerr?p0=MyApp&p1=Error%3A%2…tps%3A%2F%2Ftestvendor.planotest.com%2FScripts%2Fangular.min.js%3A17%3A315)
My js code is given below..
$(function () {
var ang = angular.module('MyApp', []);
MyApp.controller('tagReports', function ($scope) {
$scope.CustomerTagID = _TagID;
$scope.listOfTags = [];
$scope.tagList = [];
$scope.LoadCustomerDetails = function () {
$http({ method: " post", url: "/LeadManagement/Customer/GetCustomerDetailsListByTag/" + viewModel.CustomerTagID(), cache: $templateCache }).
success(function (data) {
}).
error(function (data, status) {
});
};
});
});
thank you
I guess you want to use IIFE for angualarjs with jQuery. So I have fixed the code as below
(function ($) {
var MyApp = angular.module('MyApp', []);
MyApp.controller('tagReports', function ($scope, $http, $templateCache) {
$scope.CustomerTagID = _TagID;
$scope.listOfTags = [];
$scope.tagList = [];
$scope.LoadCustomerDetails = function () {
$http({ method: " post", url: "/LeadManagement/Customer/GetCustomerDetailsListByTag/" + viewModel.CustomerTagID(), cache: $templateCache }).
success(function (data) {
}).
error(function (data, status) {
});
};
});
})(jQuery);
Hope it helps !
You need to inject $http as a dependency into your controller, like that:
MyApp.controller('tagReports', function ($scope, $http) {});

Resources