Im having problem with injections.
app.js
angular.module('Help', []);
var app = angular.module('app', [
'restangular'
,'Help'
]);
app.$inject = ['RestangularProvider'];
app.config(
function(RestangularProvider) {
RestangularProvider.setBaseUrl('http://localhost:8080/api');
}
)
help.js
function HelpCtrl($rootScope, $scope, Restangular){
Restangular.one('questions').getList();
}
HelpCtrl.$inject = ['$scope', '$rootScope','Restangular']; //"TAG1"
angular.module('Help').controller("HelpCtrl", HelpCtrl);
I get the following error:
Uncaught TypeError: Object [object Object] has no method 'one'
If I remove line TAG1, everything works. However I need to inject it the right way. What is the problem here?
The injector is used to help AngularJS know the order of parameters given to the function in case the variable name change (e.g. after minimizing your JavaScript).
In your case, you've switched up the order of your injector parameters and the method signature, meaning that AngularJS will think that $scope is $rootScope and vice versa.
Either remove your $inject or make sure the parameters are in the same order in both your method signature and in your injection array.
Related
I have configurations.js file which having
var configurationModule = angular.module('configuration', ['restangular', 'notification']);
configurationModule.factory('clientConfigSvc', function (notificationMgr, $interpolate, $injector) {
function getConfig(configKey) {
return getNestedPropertiesByString(activeEnvironment, configKey);
}
}
and having another javascript file with below code
angular.module('ds.coupons').factory('CouponsREST', ['Restangular', 'SiteConfigSvc', 'settings',function (Restangular, siteConfig, settings, configurationModule) {
configSvc.getConfig('services.baseUrl'); /// need to call this function
}
Actually i want function configSvc.getConfig inside second angular factory
Yes After tired of trying lots of solution, today morning working on moving train got idea to fix, dont know if its correct way but its working. but still looking for correct fix if mine was not correct as per angularjs practise.
Here is my solution.
1. I added configuration module in app.js alogn with other
window.app = angular.module('ds.app', [
'restangular',
'ui.select',
'ui.router',
'ds.shared',
'ds.utils',
'ds.i18n',
'configuration']);
I added clientConfigSVC in my factory where i want to use configuration function
angular.module('ds.coupons')
.factory('CouponsREST', ['Restangular', 'SiteConfigSvc','settings', 'clientConfigSvc',
function(Restangular, siteConfig, settings, clientConfig) { }
and then inside CouponsREST factory with function clientConfig.getConfig() i am getting value
At first I searched a lot about this question, used some suggestions but couldn't get results.
I had one js file, main.js, where there was only one controller and everything worked fine:
var app = angular.module('monitoringApp', ['ui.bootstrap', 'ngCookies', 'angularCharts','angularUtils.directives.dirPagination','ngLoadScript','ngRoute','dragtable']);
app.controller('mainController', ['$scope', '$http', '$cookies', '$cookieStore' , '$location', function($scope, $http, $cookies, $cookieStore,$location) {
//some function which i need to call;
}
I've added a library for drag and drop table columns dragtable.js and inside dragEnd() function I want to call some function inside main.js
var project = angular.module("dragtable", []);
project.directive('draggable', function($window, $document) {
function dragEnd($event) { need to call function inside main.js }
}
Please note that I already tried to use shared service but still getting error undefined on the function which is called.
It doesn't really matter in which file you're storing the functions. That said, a directive is unlikely to be what you're looking for as a directive is mainly used to be linked to an html element like a widget. Think of it as the controller in the MVC model scheme. It where you can have interaction from/to the ui from the coding standing point. But you can't really call a directive function directly if you don't have access to a directive.
A service on the other hand is just a singleton object that can be injected in a controller or in other places.
What you want is probably this:
project.factory('draggable', function () {
function dragEnd($event) { ... }
return dragEnd
})
And inside your main module:
app.controller('mainController',
[
'$scope'
, '$http'
, '$cookies'
, '$cookieStore'
, '$location'
, 'draggable'
, function(
$scope
, $http
, $cookies
, $cookieStore
, $location
, draggable
) {
//here you can call draggable
}]
)
Here you can see that the draggable function aka dragEnd is injected in the controller. This is good if you want to use this common function for multiple handler but then you might need to bind the function to an object like this:
var draggable = draggable.bind(someobj)
Or use it with apply or call
draggable.call(someobj, event)
draggable.apply(someobj, [event])
The reason to do that is that if you want to acces this from within the function when it's called, it might not be what it you expect it to be depending on how you're actually calling the method.
Also one note regarding your directive... You always have to return something. In you case chances are that you created the factory but didn't return anything. For this reason you had the "undefined" error. If you don'T return anything the factory will create and delete the function when it's run.
i am using angularjs 1.65 version
and its seems that $sce is getting me undefined
i have been trying serval times to get it fixed over 3 hours on it.
here is the module :
var app = angular.module('myApp', ['ui.router','ngclipboard','oitozero.ngSweetAlert']);
app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {})
and here is the controller :
app.controller('monitormainController',
['$rootScope','$scope','$timeout','SweetAlert','$sce', function
($scope,$timeout,$rootScope,$watch,SweetAlert,$sce) {
$scope.copyset = function(name){ $scope.trustedHtml =
$sce.trustAsHtml(name); };
});
i am getting an error which says $sce is undefined
Failed to load resource: the server responded with a status of 404
(File not found) angular.js:14642 TypeError: Cannot read property
'trustAsHtml' of undefined
at Scope.$scope.copyset (monitormainController.js:93)
at fn (eval at compile (angular.js:15500), :4:153)
at callback (angular.js:27285)
at Scope.$eval (angular.js:18372)
at Scope.$apply (angular.js:18472)
at HTMLButtonElement. (angular.js:27290)
at HTMLButtonElement.dispatch (jquery.js:5095)
at HTMLButtonElement.elemData.handle (jquery.js:4766)
will be happy to get any answer thank you very much!
Your dependencies are in the wrong order here. You must match the order of the dependencies in the array exactly with the parameters in the function. Also, you are expecting $watch in your function, but not including it in the dependency list.
Edit: If you are intending to use $scope.$watch rather than a $watch service that you created or installed, that isn't an injectable service. Therefore, it should not be passed as a function parameter.
Instead of:
['$rootScope','$scope','$timeout','SweetAlert','$sce', function
($scope,$timeout,$rootScope,$watch,SweetAlert,$sce) {
Try:
['$rootScope','$scope','$timeout','SweetAlert','$sce', function
($rootScope,$scope, $timeout, SweetAlert, $sce) {
I don't know why I am getting this error.
The error I am getting is Error: [ng:areq] Argument 'PreviewController' is not a function, got undefined.
Can someone help me out with this?
Also is there any other way to inject services in a controller?
My code is as follows:
(function() {
'use strict';
angular
.module('MyModule')
.controller('PreviewController' ['$scope','Service1','Service2',
function($scope, $http) {
$http.get("https://api.myjson.com/bins/30e2a")
.success(function(response) {
//Dummy data taken from JSON file
$scope.firstName = response.firstName;
$scope.lastName = response.lastName;
$scope.dateAdded = response.dateAdded;
});
//Functions have been defined. Functionality to be added.
$scope.cancelAndBack = function() {
window.history.back();
};
}]);
}());
You are defining you module incorrectly.
`angular.module('MyModule')`
Is looking for an already initialised module called 'MyModule'.
If you are creating a module from scratch you need to empty array. This would be more module dependencies.
`angular.module('MyModule', [])`
This is how angular knows the difference between, 'create an app' and 'get me an app'.
Finally services. Your using angulars array notation. That is so you can minify your javascript.
angularjs injection system works by name, that's how it can find the dependencies your require, that's also why you can list them in any order you like. However minifying your code changes your variable names and so breaks angular's injection.
The solution is to provide an array of strings telling angular the services you wish to inject and the order they are injected in.
So your array values and properties passed into your controller function must match.
Correct:
.controller('test', ["$scope", "$http", "myService", function( $scope, $http, myService){}]);
Incorrect: (myService won't be defined as its missing from the array)
.controller('test', ["$scope", "$http", function( $scope, $http, myService){}]);
From this URL https://github.com/angular/angular-seed/blob/master/app/js/app.js, I got a controller like below.
function WineListCtrl(Wine) {
this.wines = Wine.query();
}
So far what I have been doing in angular is define a controller with $scope getting injected. So i tried, changing the above controller to
function WineListCtrl(Wine, $scope) {
console.log($scope, this)
this.wines = Wine.query();
}
But this is giving an error Error: Unknown provider for '$scope'.
I have three questions here:
Why the $scope of the controller is not injected.
Does this inside the WineListCtrl means the $scope.
Most of the errors in Angular are of the format 'Unknown provider
for XXXX'. What should i look for, if the firebug says so?
You are using "inferred dependencies" (see DI page) which should work fine, unless you minify or obfuscate your JavaScript.
See my answer to this question: 'this' vs $scope in AngularJS controllers
'Unknown provider' errors normally occur when you forget to use ng-app somewhere, or you forget to initialize your app with the appropriate module:
angular js unknown provider
AngularJS linky filter throws an "Unknown Provider" error
When writing your controllers in that form you should inject them with dependencies like so:
function WineListCtrl(Wine, $scope) {
console.log($scope, this)
this.wines = Wine.query();
}
WineListCtrl.$inject = ['Wine', '$scope'];
this is not the same as $scope. $scope is an angular-specific object created with $rootScope.$new()
See #1