Below I have a simple form with a controller and service. Why is there an error thrown when I mention ['angucomplete-alt']
Html
<div ng-controller="Hell">
<input type="button" ng-click="Hello()" value="Save" />
</div>
MyApp.Js
var aap = angular.module('MyApp', ['angularUtils.directives.dirPagination','angucomplete-alt'])
aap.controller('myhmectrl', function ($scope) {
$scope.msg = "Hello Angular....";
})
Conroller.Js
(function () {
angular.module('MyApp', ['angucomplete-alt'])
.controller('Hell', function ($scope, Myservices) {
$scope.Hello = function () {
alert('ok ctrls');
var xx = Myservices.GetSer();
}
});
})
Service.Js
(function () {
angular.module('MyApp', ['angucomplete-alt'])
.service('Myservices', function ($http) {
this.GetSer = function () {
alert('pk Servicess....')
}
})
})
In controller if you are passing the dependencies it will create a new module and instantiate again, Remove the dependency
It shoule be
angular.module('MyApp').controller('Hell', function ($scope, Myservices) {
}
Maybe you didn't include js file for angucomplete-alt ?
You need to remove dependency array when you are accessing your module. Modify your files as belows:
Controller.js
(function () {
angular.module('MyApp')
.controller('Hell', function ($scope, Myservices) {
$scope.Hello = function () {
alert('ok ctrls');
var xx = Myservices.GetSer();
}
});
})
Service.js
(function () {
angular.module('MyApp')
.service('Myservices', function ($http) {
this.GetSer = function () {
alert('pk Servicess....')
}
})
})
Related
I am trying to do a file upload using angularjs. But I am getting this error for the past few days and I am unable to resolve:
angular.js:13920 Error: [$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=fileUploadServiceProvider%20%3C-%20fileUploadService%20%3C-%20appCtrl
at angular.js:38
at angular.js:4511
at Object.d [as get] (angular.js:4664)
at angular.js:4516
at d (angular.js:4664)
at e (angular.js:4688)
at Object.invoke (angular.js:4710)
at S.instance (angular.js:10354)
at p (angular.js:9263)
at g (angular.js:8620)
I only want to read the files uploaded, and store it in the server, and not to link to other URL. I am using Django for my backend. This are my codes:
HTML
<body ng-app="myApp">
<div ng-controller="appCtrl">
<input type="file" id="file" name="files" accept="text/*"
data-url="file" class="upload" ng-model="uploadFile"/>
<label for="file">
<span class="glyphicon glyphicon-open" id="selectFile">
</span>Select a file
</label>
</div>
</body>
<script src="../static/js/services/fileUploadService.js"></script>
<script src="../static/js/controllers/fileUploadController.js"></script>
<script src="../static/js/fileModel.js"></script>
Directives:
var app = angular.module('myApp', [])
app.directive("filesInput", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
Service
var app = angular.module('myApp', [])
app.factory('fileUploadService', function ($rootScope) {
var _files = [];
var service = {
add: add,
clear: clear,
upload: upload,
}
return service
function add(file){
_files.push(file)
$rootScope.$broadcast('fileAdded', file.files[0].name)
}
function clear(){
_files = []
}
function upload(){
_files.submit();
}
Controller:
var app = angular.module('myApp', [])
app.controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){
$scope.$watch('uploadFile', function (newVal, oldVal) {
var submitBtn = document.getElementById('submitBtn');
//clear existing files
fileUploadService.clear()
if(newVal == true){
var formdata = new FormData();
$scope.getTheFiles = function ($files) {
angular.forEach($files, function (value, key) {
formdata.append(key, value);
});
};
// NOW UPLOAD THE FILES.
$scope.uploadFile = function () {
var request = {
method: 'POST',
url: file,
data: formdata,
headers: {
'Content-Type': undefined
}
};
// SEND THE FILES.
$http(request)
.success(function (d) {
alert(d);
})
.error(function () {
});
}
}]);
fileUploadService.add(newVal)
fileUploadService.upload()
}
})
By using this:
var app = angular.module('myApp', [])
it creates a new module, so controller, service and directive are registered in a separate module! This results in the injection error as controller cannot inject the service, as it is registered in a different module.
The solution is to only create one module and register all the other components in it, like this:
1st file:
var app = angular.module('myApp', []);
angular.module('myApp').factory('fileUploadService', function ($rootScope) {
...
});
2nd file
angular.module('myApp').controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){
...
});
3rd file:
angular.module('myApp').directive("filesInput", function() {
...
});
Avoid multiple statements that create the module.
ERRONEOUS
var app = angular.module('myApp', [])
app.directive("filesInput", function() {
//...
});
var app = angular.module('myApp', [])
app.factory('fileUploadService', function ($rootScope) {
//...
}};
var app = angular.module('myApp', [])
app.controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){
//...
});
The extra angular.module('myApp', []) statements are overwriting existing modules, resulting in the fileUploadService becoming unregistered.
BETTER
angular.module('myApp', [])
angular.module('myApp').directive("filesInput", function() {
//...
});
angular.module('myApp').factory('fileUploadService', function ($rootScope) {
//...
}};
angular.module('myApp').controller('appCtrl', function ($scope, $rootScope, $http, fileUploadService){
//...
});
The statement creating the module must be placed before all the code adding more entities to it.
From the Docs:
Creation versus Retrieval
Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.
For more information, see
AngularJS Developer Guide - Modules - Creation versus Retrieval
AngularJS angular.module Function API Reference
I'm using angularjs and I am trying to parse a value from a service to my $scope controller. The problem is that is loading first the $scope and then the service. As a result me my scope is always undefinied. I tried many solutions that I found by no-one is worked for me. Can anyone help me please?
My service:
'use strict';
angular.module('myApp')
.service('getCategoriesService', function ($rootScope) {
getCategories = function () {
var categoriesByLocation = 1;
return categoriesByLocation;
};
and my controller:
angular.module("myApp")
.controller('MyCtrl', function ($scope,getCategoriesService) {
$scope.resultCategory = getCategoriesService.getCategories();
});
Use the this. when declaring a function in a service.
.service('getCategoriesService', function ($rootScope) {
this.getCategories = function () {
var categoriesByLocation = 1;
return categoriesByLocation;
};
})
demo
var app = angular.module("myApp",[]);
app.controller('MyCtrl', function ($scope,getCategoriesService) {
$scope.resultCategory = getCategoriesService.getCategories();
});
app.service('getCategoriesService', function ($rootScope) {
this.getCategories = function () {
var categoriesByLocation = 1;
return categoriesByLocation;
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
{{resultCategory}}
</div>
Change it as
angular.module("myApp")
.controller('MyCtrl', function ($scope,getCategoriesService) {
getCategoriesService.getCategories().then((function (d) {
$scope.resultCategory = d;
}
});
I have an angular app and I want to retain some values between controllers using angular service
Here is my base controller:
(function () {
var app = angular.module("MyApp", ["ui.router"]);
app.controller("BaseCtrl", ["$scope", "$http", "$state", BaseControllerFunc]);
function BaseControllerFunc($scope, $http, $state) {
....
}
})();
Now I want to add a service I can later fill with key-value pair data. So I tried adding the following:
app.service("DataService", function () {
var data_item = {};
data_item.Key =MyKey;
data_item.Value=MyValue;
this.MyData.push(data_item);
});
and now it looks like this:
(function () {
var app = angular.module("MyApp", ["ui.router"]);
app.controller("BaseCtrl", ["$scope", "$http", "$state", BaseControllerFunc]);
function BaseControllerFunc($scope, $http, $state) {
....
}
app.service("DataService", function () {
var data_item = {};
data_item.Key =MyKey;
data_item.Value=MyValue;
this.MyData.push(data_item);
});
})();
Here I am stuck. How would I go about injecting values (MyKey and MyValue) into my service? I am newbie with Angular so that makes it hard
Try adding functions to handle your data.
app.service("DataService", function () {
var myData = [];
function addItem(key, value){
var data_item = {Key: key, Value: value);
myData.push(data_item);
}
function getData(){
return myData;
}
return {
add: addItem,
get: getData
}
});
In your controller, use it like
DataService.add('key', 'value');
DataService.get();
change it to
app.service("DataService", function () {
var data_item = {};
return{
function somename(MyKey,MyValue){
data_item.Key =MyKey;
data_item.Value=MyValue;
this.MyData.push(data_item);
}
}
});
and from your controller call it as
DataDervice.somename(MyKey,MyValue)
When I trying call function from another file I get error:
TypeError: Cannot read property 'getCurrentUserFullName' of undefined
in app.js:
'use strict';
var testApp = {};
var App = angular.module('testApp', ['testApp.filters', 'testApp.services', 'testApp.directives',
'ngRoute']);
App.run(['$location', '$rootScope', function ($location, $rootScope) {
$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute, AuthUtils) {
if(!$rootScope.userFullName){
var userFullName = AuthUtils.getCurrentUserFullName();
if(userFullName) {
$rootScope.userFullName = userFullName;
$rootScope.authenticate = true;
} else {
$rootScope.authenticate = false;
$rootScope.userFullName = "";
}
}
});
}]);
AuthUtils.js
'use strict';
angular.module('testApp')
.factory('AuthUtils', function AuthUtils($rootScope, $http) {
return {
getCurrentUserFullName: function () {
$http.get('auth/userFullName').success(function (user) {
return user;
}).error(function (data, status) {
return "error";
console.error(status, data);
});
}
};
});
Why doesn't work?
You missed to inject AuthUtils inside run block. Inject it so factory instance would be available in run block
App.run(['$location', '$rootScope', 'AuthUtils', //<== injected AuthUtils here
function ($location, $rootScope, AuthUtils) { //<== and here
Additonally you need to remove AuthUtils parameter from $routeChangeSuccess function, which was killing existence of injected AuthUtils in run block.
Change to
$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute) //<--removed AuthUtils
From
$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute, AuthUtils)
Following Dan Wahlin's article on dynamically loading controllers and views http://weblogs.asp.net/dwahlin/archive/2013/05/22/dynamically-loading-controllers-and-views-with-angularjs-and-requirejs.aspx, I coded an sample AngularJS application with one minor modification as follows.
While Dan for example loads the data service ahead of time (main.js), I would lile to load a factory only if a controller needs it like this:
main.js
require.config({
baseUrl: '/app'
});
require([
'app',
'services/routeResolver'
//'services/mathService'
],
function () {
angular.bootstrap(document, ['myFirstApp'])
});
mathService.js
'use strict';
define(['app'], function (app) {
var mathService = function () {
return {
add: function(n1, n2) {
if (isNaN(n1) || isNaN(n2)) {
return NaN;
}
return parseInt(n1) + parseInt(n2);
}
}
};
app.factory('mathService', mathService);
});
v2Controller.js
'use strict';
define(['app', 'services/mathService'], function (app) {
var ctrl = function ($scope, mathService) {
$scope.greeting = 'Hi there from viewtwoland!';
$scope.n1 = 0;
$scope.n2 = 0;
$scope.result = 0;
$scope.add = function ()
{
$scope.result = mathService.add($scope.n1, $scope.n2);
}
};
app.register.controller('v2Controller', ['$scope', 'mathService', ctrl]);
});
v2.html
<p>
{{greeting}}
</p>
<input type="text" data-ng-model="n1" id="n1" name="n1" data-ng-change="add()" />
<input type="text" data-ng-model="n2" id="n2" name="n2" data-ng-change="add()" />
<div>
The sum of {{n1}} and {{n2}} is: {{result}}
</div>
This is however not working as expected. Here is the result I am getting:
{{greeting}}
[ ] [ ]
The sum of {{n1}} and {{n2}} is: {{result}}
Any ideas. Is this doable at all.
I resolved the issue by changing the controller as follows:
define(['app', 'services/mathService'], function (app) {
var ctrl = function ($scope, mathService) {
$scope.greeting = 'Hi there from viewtwoland!';
$scope.n1 = 0;
$scope.n2 = 0;
$scope.result = 0;
$scope.add = function ()
{
return mathService.add($scope.n1, $scope.n2);
}
};
app.register.controller('v2Controller', ['$scope', 'mathService', ctrl]);
});
and the mathService as follows:
'use strict';
define(['app'], function (app) {
var mathService = function () {
return {
add: function(n1, n2) {
if (isNaN(n1) || isNaN(n2)) {
return NaN;
}
return parseInt(n1) + parseInt(n2);
}
}
};
app.register.factory('mathService', mathService);
});
If you have a better solution for this issue, I'd be interesting in knowing it.