I am having a hard time to access a service inside a directive. I define my service via $http and $q, and inject it into my directive. But I can;t get the directive to access the service.
service.js
'use strict';
var app = angular.module('App.services', []);
app.factory('Classification', function($http,$q) {
return {
query: function getAll() {
var deferred = $q.defer();
$http.get('index.php/classifications').then(function(classi) {
deferred.resolve(classi.data);
}, function getWebsitesError(reason) {
deferred.reject(reason);
});
return deferred.promise;
}
};
});
app.js
'use strict';
/* App Module */
var app = angular.module('App', ['App.controllers', 'App.services', 'App.directives', 'ui']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl: 'partials/welcome.html'}).
when('/websites/:websiteId', {templateUrl: 'partials/website/details.html', controller: 'WebsiteDetailsCtrl'}).
otherwise({redirectTo: '/'});
}]);
and my directive.js :
'use strict';
var app = angular.module('App.directives', ['App.services']);
app.directive("regionselect",['Classification', '$compile', function($compile, Classification){
Classification.query();<-- Throw an exception : has no method query()
return{
restrict : "E",
templateUrl : "/js/directives/locationSelect3.html",
transclude: true,
compile: function (tElement, tAttr, transclude){
var loaded = false;
}
};
}]);
Any idea what I am doing wrong?
Could it be the ordering?
app.directive("regionselect",['Classification', '$compile', function($compile, Classification){
You declare
['Classification', '$compile',
but the the function says
function($compile, Classification){
Which is backwards.
Related
I'm trying to get the data from a json file.
i have a file, factory1.js
myApp.factory('mainInfo', [
'$http',
function($http) {
return {
get: function(){
$http.get('data.json');
}
}}])
and then i have another file, view1.js
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', [
'$scope',
'$http',
'mainInfo',
function($scope, $http, mainInfo) {
mainInfo.get("data.json")
.then(function(response) {
$scope.myWelcome = response.data;
console.log($scope.myWelcome)
});
}]);
i have one folder with each of the json, factory and controller files in it.
when i run this the error it is returning says...
angular.js:13708 Error: [$injector:unpr] Unknown provider: mainInfoProvider <- mainInfo <- View1Ctrl
where am i going wrong?
Working fine. This solves your problem i hope so.
'use strict';
var app=angular.module('myApp.view1', ['ngRoute'])
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
app.factory('mainInfo',
function($http) {
var obj={};
obj.method =function(){
return $http.get('tag.json')
}
return obj;
})
app.controller('View1Ctrl', [
'$scope',
'$http',
'mainInfo',
function($scope, $http, mainInfo) {
mainInfo.method().success(function(response) {
$scope.myWelcome = response;
});
}]);
var app=angular.module('myApp.view1', ['ngRoute']);
app.factory('mainInfo', [
'$http',
function($http) {
return {
get: function(){
$http.get('data.json');
}
}}])
define one variable and assign your module to that variable and bind the variable to the factory.if you have module with name myApp inject that module in to myapp.view1 module
like
angular.module('myApp.view1', ['ngRoute','myApp'])
Register mainInfo inside Angular module, if it's a different module.
view1.js
angular.module('myApp.view1', ['ngRoute', 'myApp']);
You have not assigned your module to a variable.
var myApp = angular.module('myApp.view1', ['ngRoute']) ...
Then use myApp.factory
myApp.factory('mainInfo', [...
see this plunkr for quick understanding.
The app runs on http://domain1 an must request data from http://domain2 with the following code:
'use strict';
// Declare app level module which depends on views, and components
var myApp = angular.module('myApp', [
'ngRoute',
'restangular'
]);
myApp.config(['$routeProvider', 'RestangularProvider', function($routeProvider, RestangularProvider) {
$routeProvider.when('/view1', {
templateUrl: '/view1.html',
controller: 'View1Ctrl'
});
$routeProvider.otherwise({redirectTo: '/view1'});
RestangularProvider.setBaseUrl("http://domain2/");
}]);
var rest = null;
myApp.controller('View1Ctrl', ['$scope', 'Restangular', function($scope, Restangular) {
rest = Restangular;
var cursos = Restangular.one("resource",100).get()
}]);
Nonetheless, the request goes to http://domain1. What is going on? I also inspected the Restangular configuration, by putting Restangular in the global scope, as the rest variable, and the base url seems is property set.
Hey you can create a factory and use different domain to get data something like below
(function () {
'use strict';
angular.module('app')
.factory('Domain2Restangular', ['Restangular', Domain2RestangularFunction]);
function Domain2RestangularFunction( Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
var baseURL = 'http://domain2';
RestangularConfigurer.setBaseUrl(baseURL);
RestangularConfigurer.setDefaultHeaders({'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' });
});
}
}());
You can invoke
return Domain2Restangular.all('')
.post(data)
.then(function(response) {
return response;
}, function(error) {
return error
});
I have sample on Angular JS as:
angular.module('wm-admin', []).
config(function($routeProvider) {
$routeProvider.
when('/users', {controller:UsersController, templateUrl:'/public/html/crm/users/list.html'}).
otherwise({redirectTo:'/users'});
});
// Controllers //
function UsersController($scope) {
}
It gives me error:
Uncaught Error: [$injector:modulerr]
So, what I do wrong?
HTML:
<body ng-app="wm-admin">
</body>
I tried also any code:
Angular JS:
(function (angular) {
'use strict';
angular.module('wm-admin', [])
.config(function($routeProvider) {
$routeProvider.
when('/users', {controller:UsersController, templateUrl:'/public/html/crm/users/list.html'}).
otherwise({redirectTo:'/users'});
})
// Controllers //
.controller('UsersController', ['$scope', '$http', function ($scope, $http) {
}])
})(window.angular);
Look please code upper
You haven't injected the controller properly to your app. Add this line:
angular.module('wm-admin').controller('UsersController', UsersController);
EDIT
In your updated question you have this code:
(function (angular) {
'use strict';
angular.module('wm-admin', [])
.config(function($routeProvider) {
$routeProvider.
when('/users', {controller:UsersController, templateUrl:'/public/html/crm/users/list.html'}).
otherwise({redirectTo:'/users'});
})
// Controllers //
.controller('UsersController', ['$scope', '$http', function ($scope, $http) {
}])
})(window.angular);
But now UsersController is no longer a function within the scope of the {controller: UsersController} line. Change it to controller: 'UsersController' (string, not reference to a function):
(function (angular) {
'use strict';
angular.module('wm-admin', [])
.config(function($routeProvider) {
$routeProvider.
when('/users', {controller: 'UsersController', templateUrl:'/public/html/crm/users/list.html'}).
otherwise({redirectTo:'/users'});
})
// Controllers //
.controller('UsersController', ['$scope', '$http', function ($scope, $http) {
}])
})(window.angular);
You never actually made a controller.
angular
.module('wm-admin')
.controller('UsersController', UsersController);
UsersController.$inject = ['$scope'];
function UsersController($scope) {
}
I am having an issue with testing a routeProvider. There seems to be a lot of information out there, but everything I do, I just cannot get the unit test to digest the location. I was hoping to find some closure here. I am feeling my way through angularJS and unit testing, and could use any advice.
Here is the routeProvider function:
use strict';
var myApp = angular.module('myApp', [
'ngRoute',
'myServices',
'myControllers'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('fooBar', {
templateUrl: 'barFoo',
controller: 'SummaryCtrl'
}).
otherwise({
redirectTo: 'defaultFooBar'
});
}]);
I am trying to test this routeProvider with the following, but I cannot, for the life of my, inject the change I make to location.
'use strict';
describe('myApp',function() {
var $scope;
var location;
beforeEach(inject(function($rootScope, $location) {
$scope = $rootScope;
location = $location;
}));
it('redirect to default', function() {
location.path('efipoejs');
$scope.$apply();
expect(location.path()).toBe('defaultFooBar');
})
});
Ive tried $scope.$digest, and .$apply.... what ever I do, I always get this outcome:
Expected '/efipoejs' to be 'defaultFooBar'.
I really want angularJS to work... If you have any advice that might lead me down the right path...I would seriously appreciate it.
ANSWER: BECAUSE I CANT POST AN ANSWER WITHIN 8 HOURS!!!!
yo yea,...
Here's how I got this to work
describe('Testing routes', function() {
beforeEach(module('myApp'));
var location, route, rootScope;
beforeEach(inject(
function( $location, $route, $rootScope ) {
location = $location;
route = $route;
rootScope = $rootScope;
}));
describe('Default Routing', function() {
beforeEach(inject(
function($httpBackend) {
$httpBackend.expectGET('DefaultUrl').respond(200);
}));
it('should load the default page on fake path', function() {
location.path('/ermagerd');
rootScope.$digest();
expect(location.path()).toBe('defaultFooBar');
});
});
});
});
Once again, here is my logic
'use strict';
var myApp = angular.module('myApp', [
'ngRoute',
'myServices',
'myControllers'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('fooBarDefault', {
templateUrl: 'defaultUrl',
controller: 'DefaultCtrl'
}).
otherwise({
redirectTo: 'fooBarDefault'
});
}]);
I can't seem to wire this up properly. I'll list the appropriate pieces. My issue is accessing the injected resources. All of the dependent pieces are undefined when I try to reference them.
var app = angular.module('app', ['ngResource','ui.bootstrap', 'ngGrid','app.services', 'app.directives', 'app.controllers'
])
.config(['$routeProvider', function ($routeProvider) {
return $routeProvider.
when('/', { templateUrl: 'partials/transaction.view.html', controller: 'TransactionCtrl' }).
when('/about', { templateUrl: 'partials/about.view.html', controller: 'AboutCtrl' }).
when('/transaction', { templateUrl: 'partials/transaction.view.html', controller: 'TransactionCtrl' }).
otherwise({ redirectTo: '/' });
}])
.config(['$httpProvider', function ($httpProvider) {
return $httpProvider.responseInterceptors.push(['logger', '$rootScope', '$q',
function (logger, $rootScope, $q) {
var error, success;
success = function (response) {
$rootScope.$broadcast("success:" + response.status, response);
logger.log("success:" + response.status);
return response;
};
error = function (response) {
var deferred;
deferred = $q.defer();
$rootScope.$broadcast("error:" + response.status, response);
logger.log("error:" + response.status);
return $q.reject(response);
};
return function (promise) {
return promise.then(success, error);
};
}
]);
}])
.run(['$rootScope', 'logger', function ($rootScope, logger) {
return $rootScope.$on('$routeChangeSuccess', function (event, currentRoute, priorRoute) {
return $rootScope.$broadcast("" + currentRoute.controller + "$routeChangeSuccess", currentRoute, priorRoute);
});
}]);
...the controllers are here:
angular.module('pennyWatch.controllers', ['$scope', '$location','logger', 'ngGrid', 'transactionService']).
controller('TransactionCtrl', [function ($scope, logger, ngGrid, transactionService) {
//code here
}]).
controller('AboutCtrl',[function ($scope, logger) {
$scope.logEntries = logger.logEntries;
}]);
So none of the resources I specified are available (all undefined): '$scope', '$location','logger', 'ngGrid', 'transactionService'
Any light shed on this would be greatly appreciated!
Thanks
I'm pretty sure the syntax for a controller is:
.controller('TransactionCtrl', ['$scope', 'logger', 'ngGrid', 'transactionService', function ($scope, logger, ngGrid, transactionService) {
//code here
}]);
You first list what to inject, then as the last element of the array to define a function with parameters that will represent what's injected.
For instance you could even have:
.controller('TransactionCtrl', ['$scope', 'logger', 'ngGrid', 'transactionService', function ($s, logr, ngGrid, transServ) {
//code here
}]);
This is to allow for easy minification.
The alternative controller syntax uses the parameter names when choosing what to inject. And since minification usually involves shortening variable names, it's suggested you use the syntax above.
Alternative syntax:
.controller('TransactionCtrl', function ($scope, logger, ngGrid, transactionService) {
//code here
});
I think you are swapping module-loading with service-injection
when declaring the pennywatch.controllers module, you should invoke the angular.module function passing the module dependencies in brackets, not the services. many of the services you cannot access are in the ng module, for instance
service injection is applied at the controller level