Testing on angular $resource query shows error of ngResourceProvider not found - javascript

<script src="/library/angularjs/1.2.0-rc.3/angularjs.js"></script>
<script src="/library/angularjs/1.2.0-rc.3/angular-route.js"></script>
<script src="/library/angularjs/1.2.0-rc.3/angular-resource.js"></script>
<script>
var app= angular.module('myApp', ['ngRoute', 'ngResource']);
app.service('Greeter', ['$resource',function($resource){
return $resource(
'http://123.com/processor.php',
{callback: 'JSON_CALLBACK'},
{
query: {method:'JSON_CALLBACK',isArray:true}
});
}]);
app
.controller('MyCtrl', ['$scope', 'Greeter',
function($scope,Greeter){
alert("yes");
$scope.greet = function(){
alert("greetttt");
Greeter.query({name:this.name}, function(response){
alert(response.greeting);
});
};
}]);
</script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
Your name:
<input type="text" name="name" value="World"/>
<button ng-click="greet()">greet</button>
</div>
</div>
The PHP file simply throw out a JSON array, but I saw chrome inspectors tells me that:
Error: [$injector:unpr] Unknown provider: $resourceProvider <- $resource <- Greeter
I wonder if there is any syntax error? As the PHP do throw out a valid JSON array.
Thanks
Update1----
I update the code shows that I loaded the resource and angular in the right order.
After Bielski's fix, still, there is error shows (same error)
Error: [$injector:unpr] Unknown provider: $resourceProvider <- $resource <- Greeter
Update 2
After runTarm fix, The only trouble now seems the way I reference Greeter is not correct...
ReferenceError: Greeter is not defined
at Scope.$scope.greet (http://123.com/index-query.php:21:5)
which represent this line:
Greeter.query({name:this.name}, function(response){
Update 3
After suggested adding Greeter ad resource, still, the error of below will appear:
TypeError: undefined is not a function
at Scope.$scope.greet (http://123.com/index-query.php:21:13)
Seemingly something is wrong between these 3 lines
$scope.greet = function(){
alert("greetttt");
Greeter.query({name:this.name}, function(response){

You have to include the ngResource in your module's dependency list like this:
var app = angular.module('myApp', ['ngRoute', 'ngResource']);
Another thing is about the greet() function, when you bind a function in ng-click like this:
<button ng-click="greet()">
Angular will look for the greet() function in the controller's scope, but you define the greet() in the controller instance itself.
One way is to move the greet() function into the $scope like this:
app
.controller('MyCtrl', ['$scope', 'Greeter',
function($scope, Greeter){
alert("yes");
$scope.greet = function(){
alert("greetttt");
Greeter.query({name:this.name}, function(response){
alert(response.greeting);
});
};
}]);

The $resource provider isn't being loaded and/or referenced correctly. Two things:
First, you need to make sure that the file 'angular-resource.js' is being loaded in your page, and that it appears in the list of scripts to be loaded BEFORE you load your app.
Second, try setting your service up like this:
app.service('Greeter', ['$resource', function($resource){
return $resource(
'http://123.com/processor.php',
{callback: 'JSON_CALLBACK'},
{
query: {method:'JSON_CALLBACK',isArray:true}
});
}]);
This will give you protection from minification errors and it is sometimes eaiser to spot which providers are missing using this format.

You forgot to add Greeter to the controller function's arguments
app
.controller('MyCtrl', ['$scope', 'Greeter',
function($scope, Greeter){
alert("yes");
$scope.greet = function(){
alert("greetttt");
Greeter.query({name:this.name}, function(response){
alert(response.greeting);
});
};
}]);

Related

Cant display $scope array of objects in AngularJs

I have this weird problem that i cant display my scope variable values. I am new with angular but i have done this many times before. So here is main parts of index.html. div-ui is inside of body but it doesn't see here:
<input type="text" class="form-control" ng-model="searchUsers" placeholder="Search users"/>
<a ng-click="search()" ui-sref="search">Search</a>
<div ui-view>
</div>
Here is search.html:
<p>Hello world</p> // Shows normally
<p>{{test1}}</p> // Shows normally
<p>{{test2}}</p> // Nothing
<p ng-repeat="x in searchResult">{{x.username}}</p> // Nothing
<p ng-repeat="(key,value) in searchResult">{{value}}</p> // Nothing
<p ng-repeat="(key,value) in searchResult">{{value.username}}</p> // Nothing
Here is the controller:
(function(){
angular.module('TimeWaste')
.controller('NavigationCtrl', ["$scope", "$http", "$state",
function($scope,$http,$state){
$scope.searchResult = [];
// Tried with and without this
if(localStorage['User-Data']){
$scope.loggedIn = true;
}else{
$scope.loggedIn = false;
}
$scope.logUserIn = function(){
$http.post('api/user/login', $scope.login)
.success(function(response){
localStorage.setItem('User-Data', JSON.stringify(response));
$scope.loggedIn = true;
}).error(function(error){
console.log(error);
});
}
$scope.logOut = function (){
localStorage.clear();
$scope.loggedIn = false;
}
$scope.test1 = "hi";
$scope.search = function (){
$scope.test2 = "hi again";
$http.post("api/user/search", {username: $scope.searchUsers})
.success(function(response){
$scope.searchResult = response;
console.log($scope.searchResult);
// returns array of objects. There is all information that i want.
}).error(function(error){
console.log("ei");
});
}
}]);
}());
Everything looks just normal. Inside of search function it's working and console.log returns just what i except. I have also tried repeat divs and tables but i am pretty sure that it's not the problem here.
Here is also my app.js if the problem is there:
(function(){
angular.module('TimeWaste', ['ui.router', 'ngFileUpload'])
.config(function ($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("/");
$stateProvider
.state("main", {
url: "/",
templateUrl: "app/main/main.html",
controller: "MainCtrl"
})
.state("search", {
url: "/search",
templateUrl: "app/main/search.html",
controller: "NavigationCtrl"
})
});
}());
There is couple more states and they all works just fine. I made it little bit shorter so this post won't be so long.
The reason you're able to see {{test1}} and not other values is because you have 2 different controllers called 'MainCtrl' and 'NavigationCtrl'. You are using ui-sref to switch states. So, this is what happening.
When you click your href link, it looks for search() method inside your MainCtrl and then change the state to "search".
It then loads the variables and methods from NavigationCtrl into scope and that's why you're able to see {{test1}} which is loaded into the scope. But you haven't called search() method and hence you're not able to see the other values.
To check my answer, call your method explicitly inside your controller after your function definition $scope.search();
If you're seeing the result then that is your problem.
OK, at this very point you must add an $scope.$apply or use '.then' instead of 'success' to keep your code according promise pattern.
When you just post, there is a need to force the digest cycle to happen.
$http.post("api/user/search", {username: $scope.searchUsers})
.success(function(response){
$scope.$apply(function() {
$scope.searchResult = response;
});
}).error(function(error){
console.log("ei");
});

Angular JS Controller Not Being Instantiated

I have this angular app that I am running off only one webpage of my site.
I have a main application that uses another module I made as a dependency.
The problem I am having is that nothing inside my controller is being ran. Why won't my controller run?
My route does bring in the view however so I know that the module is working.
I got rid of my data service to be certain that it was not it.
The console.log before the function outputs, but nothing in the function runs.
I also have no console errors.
app.js:
(function(){
'use strict';
var dependencies = [
'ghpg',
'ngRoute'
];
angular.module('blogger', dependencies)
.config(Config);
Config.$inject = ['$locationProvider']
function Config($locationProvider){
$locationProvider.hashPrefix('!');
}
if (window.location.hash === '#_=_'){
window.location.hash = '#!';
}
//bootstrap angular
angular.element(document).ready(function(){
angular.bootstrap(document, ['ghpg']);
});
})();
module:
(function(){
'use strict';
var dependencies = [ 'ngRoute' ];
angular.module('ghpg', dependencies)
.run(init)
init.$inject = ['$rootScope','$location' ];
function init($rootScope, $location){
var vm = this;
}
})();
View:
<div class="container-fluid" data-ngController="blogController as vm">
<h2> Articles </h2>
<div class="post-listing" data-ng-repeat=" post in vm.data">
<p> {{ post }} </p>
</div>
</div>
Controller:
(function(){
'use strict';
angular
.module('ghpg')
.controller('blogController', blogController);
blogController.$inject = ['$scope'];
////
console.log("In controller file");
function blogController($scope){
console.log('running controller');
var vm = this;
vm.data = blogContent.getContent();
console.log(vm.data);
}
})();
I am wondering if it has something to do with bootstrapping my application? (But it all still works even without the explicit ng-app, so I am thinking that my bootstrapping does work)
My next best guess is that my controller in my html is not being set correctly, but every time I mess with it I either get the same result or an error in the console, and it still doesn't work.
blogController.$inject = ['$scope','blogController']
you're trying to inject your controller into your controller. Change it to
blogController.$inject = ['$scope'] and function blogController($scope).
Did you mean to write? blogController.$inject = ['$scope','blogContent']
I see you're calling a method on blogContent and I don't see it injected anywhere.
Edit
data-ngController should be data-ng-controller.

How to add multiple controller in single page in AngularJS

I am new to AngularJS I have a problem with this code. I want to add multiple controller in single ng-app. But it execute first one. Why not second one?
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angul /1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-controller="cont1">
<input type="text" ng-model="fullname">
{{fullname}}
</div>
<div ng-controller="cont2">
<input type="text" ng-model="fname">
{{fname}}
</div>
<script>
var app = angular.module("myapp", []);
app.controller('cont1', function ($scope) {
$scope.fullname = "";
});
var new = angular.module('myapp', []);
new.controller('cont2', function ($scope) {
$scope.fname = "";
});
</script>
</body>
</html>
Because you are overwriting the first myapp module when you do var new= angular.module('myapp',[]);.
Your code should be:
var app = angular.module("myapp", []);
app.controller('cont1', function($scope) {
$scope.fullname = "";
});
app.controller('cont2', function($scope) {
$scope.fname = "";
});
or
var app = angular.module("myapp", []);
app.controller('cont1', function($scope) {
$scope.fullname = "";
});
angular.module("myapp").controller('cont2', function($scope) {
$scope.fname = "";
});
The second parameter[] passed to module() makes the difference
To best way to define controllers, directives, factories etc... is
define your modules names in a separate file
app.module.js
angular.module("myapp",[]); // inside [] you define your module dependencies
for controllers create separate file (depending on your requirement even you can create 1 file for 1 controller)
some.controller.js
angular.module("myapp").controller('someCtrl'['$scope', function($scope){
}]);
angular.module("myapp").controller('someOtherCtrl'['$scope', function($scope){
}]);
NOTE:
Two types you can write controller
TYPE1 (not recomended)
.controller('ctrlName', function($scope){
});
TYPE2 (recomended)
.controller('ctrlName', ['$scope', function($scope){
}]);
Reason
So as you can see in the TYPE2 we are passing controller dependencies in an array, so when we compile our program angular will give the name as eg:a to $scope inside function() and treat it as $scope.
With the TYPE1 you need to follow specific order while defining controller dependency otherwise angular will through error because in this approach angular simply treats first dependency as $rootscope, second as $scope and so on....
For Eg:
you can't pass dependencies to your controller like this
.controller('ctrlName', function($http, $scope) {
});
this will throw error
if you define like
.controller('ctrlName', function($scope, $http) {
});
this will work fine since its in order that angular wants.
You can define multiple controllers in a single module in this way also:
angular.module("myapp",[]);
.controller('cont1',function($scope){
$scope.fullname="";
});
.controller('cont2',function($scope){
$scope.fname="";
});
When you are defining modules, don't use var. You can find some of the Angular best practices here: Angular Style Guide/Best Practices

AngularJs Loading separate controllers

I have each of my angular controllers/services in separate folders (taken from angular seed).
I need to call different controllers on different pages.
I am getting errors that ***Ctrl is not loading. How do I 'inherit' controllers specific to each page?
Here is my current structure.
// Index.html
<script>app.js</script>
<div ng-app='myApp'>
<div ng-controller='headerCtrl'> Load user profile on every page</div>
</div>
// TaskList.html
<script>app.js</script>
<script>task.js</script>
<div ng-app='myApp'>
<div ng-controller='headerCtrl'>Load user profile on every page</div>
<div ng-controller='taskCtrl'> Load task list </div>
</div>
// ProjectList.html
<script>app.js</script>
<script>project.js</script>
<div ng-app='myApp'>
<div ng-controller='headerCtrl'>Load user profile on every page</div>
<div ng-controller='projectCtrl'>Load task list</div>
</div>
// app.js
var myApp = angular.module('myApp', []);
myApp.controller('headerCtrl', function ($scope, $window) {
// do stuff
});
// task.js
var taskCtrl = angular.module('taskCtrl', []);
taskCtrl.controller('taskCtrl', function ($scope, $window) {
// do stuff
});
// project.js
var projectCtrl = angular.module('projectCtrl', []);
projectCtrl.controller('projectCtrl', function ($scope, $window) {
// do stuff
});
Unless you have a good reason to do, I would recommend just putting your controllers in the same module. You can reference your taskApp module in other files (task.js and project.js) by doing the following:
var taskApp = angular.module('taskApp');
taskApp.controller('taskCtrl, ...);
Note that the call to angular.module has only one parameter - that's telling Angular that you want to get a reference to an existing module, rather than create a new module. On the other hand, doing this:
var taskApp = angular.module('taskApp', []);
Is telling Angular that you want to create a new module (with no dependencies). Subtle but very important difference.
That's because you're putting each controller in a separate module, but only referencing myApp , you need to inject the other app dependencies to your main app. Also, why are you storing your app and controllers in the same object? No wonder you're getting errors. Do this instead:
var taskApp = angular.module('taskApp', []);
taskApp.controller('taskCtrl', function ($scope, $window) {
// do stuff
});
var projectApp = angular.module('projectApp', []);
projectApp.controller('projectCtrl', function ($scope, $window) {
// do stuff
});
var myApp = angular.module('myApp', ['taskApp','projectApp']);

Error: [ng:areq] from angular controller

This is a long shot, but has anyone seen this error before? I am trying to add 'Transporters' using express, angular and mongoDB. I get this error whenever I access a page ruled by the transporters controller:
Error: [ng:areq] http://errors.angularjs.org/1.2.12/ng/areq?p0=TransportersController&p1=not%20aNaNunction%2C%20got%20undefined
at Error (native)
at http://localhost:3000/lib/angular/angular.min.js:6:450
at tb (http://localhost:3000/lib/angular/angular.min.js:18:360)
at Pa (http://localhost:3000/lib/angular/angular.min.js:18:447)
at http://localhost:3000/lib/angular/angular.min.js:62:17
at http://localhost:3000/lib/angular/angular.min.js:49:43
at q (http://localhost:3000/lib/angular/angular.min.js:7:386)
at H (http://localhost:3000/lib/angular/angular.min.js:48:406)
at f (http://localhost:3000/lib/angular/angular.min.js:42:399)
at http://localhost:3000/lib/angular/angular.min.js:42:67
The transporters controller looks like this:
'use strict';
angular.module('mean.transporters').controller('TransportersController', ['$scope', '$routeParams', '$location', 'Global', 'Transporters', function ($scope, $routeParams, $location, Global, Transporters) {
$scope.global = Global;
$scope.create = function() {
var transporter = new Transporters({
name: this.name,
natl_id: this.natl_id,
phone: this.phone
});
transporter.$save(function(response) {
$location.path('transporters/' + response._id);
});
this.title = '';
this.content = '';
};
$scope.remove = function(transporter) {
if (transporter) {
transporter.$remove();
for (var i in $scope.transporters) {
if ($scope.transporters[i] === transporter) {
$scope.transporters.splice(i, 1);
}
}
}
else {
$scope.transporter.$remove();
$location.path('transporters');
}
};
$scope.update = function() {
var transporter = $scope.transporter;
if (!transporter.updated) {
transporter.updated = [];
}
transporter.updated.push(new Date().getTime());
transporter.$update(function() {
$location.path('transporters/' + transporter._id);
});
};
$scope.find = function() {
Transporters.query(function(transporters) {
$scope.transporters = transporters;
});
};
$scope.findOne = function() {
Transporters.get({
transporterId: $routeParams.transporterId
}, function(transporter) {
$scope.transporter = transporter;
});
};
}]);
In my views I call the list and create methods. They generate the above error
I got this from the angular docs for ng:areq though still can't figure what's going on
AngularJS often asserts that certain values will be present and truthy
using a helper function. If the assertion fails, this error is thrown.
To fix this problem, make sure that the value the assertion expects is
defined and truthy.
Here's the view that calls the controller public/views/transporters/list.html:
<section data-ng-controller="TransportersController" data-ng-init="find()">
<ul class="transporters unstyled">
<li data-ng-repeat="transporter in transporters">
<span>{{transporter.created | date:'medium'}}</span> /
<h2><a data-ng-href="#!/transporters/{{transporter._id}}">{{transporter.name}}</a></h2>
<div>{{transporter.natl_id}}</div>
<div>{{transporter.phone}}</div>
</li>
</ul>
<h1 data-ng-hide="!transporters || transporters.length">No transporters yet. <br> Why don't you Create One?</h1>
</section>
Transporters service code:
angular.module('transporterService', [])
.factory('Transporter', ['$http', function($http){
// all return promise objects
return {
get: function(){
return $http.get('/api/transporters');
},
create: function(transporterData){
return $http.post('/api/transporters', transporterData);
},
delete: function(id){
return $http.delete('/api/transporters/'+id);
}
};
}]);
I experienced this error once. The problem was I had defined angular.module() in two places with different arguments.
Eg:
var MyApp = angular.module('MyApp', []);
in other place,
var MyApp2 = angular.module('MyApp', ['ngAnimate']);
I've gotten that error twice:
1) When I wrote:
var app = module('flapperNews', []);
instead of:
var app = angular.module('flapperNews', []);
2) When I copy and pasted some html, and the controller name in the html did not exactly match the controller name in my app.js file, for instance:
index.html:
<script src="app.js"></script>
...
...
<body ng-app="flapperNews" ng-controller="MainCtrl">
app.js:
var app = angular.module('flapperNews', []);
app.controller('MyCtrl', ....
In the html, the controller name is "MainCtrl", and in the js I used the name "MyCtrl".
There is actually an error message embedded in the error url:
Error: [ng:areq]
http://errors.angularjs.org/1.3.2/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined
Here it is without the hieroglyphics:
MainCtrl not a function got undefined
In other words, "There is no function named MainCtrl. Check your spelling."
I ran into this issue when I had defined the module in the Angular controller but neglected to set the app name in my HTML file. For example:
<html ng-app>
instead of the correct:
<html ng-app="myApp">
when I had defined something like:
angular.module('myApp', []).controller(...
and referenced it in my HTML file.
you forgot to include the controller in your index.html. The controller doesn't exist.
<script src="js/controllers/Controller.js"></script>
I had same error and the issue was that I didn't inject the new module in the main application
var app = angular.module("geo", []);
...
angular
.module('myApp', [
'ui.router',
'ngResource',
'photos',
'geo' //was missing
])
Check the name of your angular module...what is the name of your module in your app.js?
In your TransportersController, you have:
angular.module('mean.transporters')
and in your TransportersService you have:
angular.module('transporterService', [])
You probably want to reference the same module in each:
angular.module('myApp')
I had this error too, I changed the code like this then it worked.
html
<html ng-app="app">
<div ng-controller="firstCtrl">
...
</div>
</html>
app.js
(function(){
var app = angular.module('app',[]);
app.controller('firstCtrl',function($scope){
...
})
})();
You have to make sure that the name in module is same as ng-app
then div will be in the scope of firstCtrl
The same problem happened with me but my problem was that I wasn't adding the FILE_NAME_WHERE_IS_MY_FUNCTION.js
so my file.html never found where my function was
Once I add the "file.js" I resolved the problem
<html ng-app='myApp'>
<body ng-controller='TextController'>
....
....
....
<script src="../file.js"></script>
</body>
</html>
:)
I've got that error when the controller name was not the same (case sensitivity!):
.controller('mainCOntroller', ... // notice CO
and in view
<div class="container" ng-controller="mainController"> <!-- notice Co -->
I got this same error when I included the entire controller file name in the Routes like this:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'mainController.js'
})
.when('/portfolio', {
templateUrl: 'portfolio.html',
controller: 'mainController.js'
})
});
When it should be
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'mainController'
})
.when('/portfolio', {
templateUrl: 'portfolio.html',
controller: 'mainController'
})
});
Angular takes certain things you name like the app and controller and expounds on them in directives and across your app, take care to name everything consistently and check for this when debugging
I know this sounds stupid, but don't see it on here yet :). I had this error caused by forgetting the closing bracket on a function and its associated semi-colon since it was anonymous assigned to a var at the end of my controller.
It appears that many issues with the controller (whether caused by injection error, syntax, etc.) cause this error to appear.
This happened to me when I have multiple angular modules in the same page
I encountered this error when I used partial views
One partial view had
<script src="~/Scripts/Items.js"></script>
<div ng-app="SearchModule">
<div ng-controller="SearchSomething" class="col-md-1">
<input class="searchClass" type="text" placeholder="Search" />
</div>
</div>
Other had
<div ng-app="FeaturedItems" ng-controller="featured">
<ul>
<li ng-repeat="item in Items">{{item.Name}}</li>
</ul>
</div>
I had them in same module with different controller and it started working
I had the same error in a demo app that was concerned with security and login state. None of the other solutions helped, but simply opening a new anonymous browser window did the trick.
Basically, there were cookies and tokens left from a previous version of the app which put AngularJS in a state that it was never supposed to reach. Hence the areq assertions failed.
There's also another way this could happen.
In my app I have a main module that takes care of the ui-router state management, config, and things like that. The actual functionality is all defined in other modules.
I had defined a module
angular.module('account', ['services']);
that had a controller 'DashboardController' in it, but had forgotten to inject it into the main module where I had a state that referenced the DashboardController.
Since the DashboardController wasn't available because of the missing injection, it threw this error.
In my case I included app.js below the controller while app.js should include above any controller like
<script src="js/app.js"></script>
<script src="js/controllers/mainCtrl.js"></script>
I had done everything right other than setting controller in $stateProvider. I used filename rather than variable name.
Following code is wrong:
formApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('management', {
url: '/management',
templateUrl: 'Views/management.html',
controller: 'Controllers/ManagementController.js'
});
and this is the right approach;
formApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('management', {
url: '/management',
templateUrl: 'Views/management.html',
controller: 'ManagementController'
});
Make sure you noticed;
controller: 'ManagementController'
And for those who are curious about my controller file ManagementController.js, it looks like the this;
formApp.controller('ManagementController', ['$scope', '$http', '$filter', '$state',function(scope, http, filter, state) {
scope.testFunc = function() {
scope.managementMsg = "Controller Works Fine.";
};
}]);
For those who want a quick-start angular skeleton for above example check this link https://github.com/zaferfatih/angular_skeleton
The error will be seen when your controller could not be found in the application. You need to make sure that you are correct using values in ng-app and ng-controller directives
This happened to me when using ng-include, and the included page had controllers defined. Apparently that's not supported.
Controller loaded by ng-include not working
I have made a stupid mistake and wasted lot of time so adding this answer over here so that it helps someone
I was incorrectly adding the $scope variable(dependency)(was adding it without single quotes)
for example what i was doing was something like this
angular.module("myApp",[]).controller('akshay',[$scope,
where the desired syntax is like this
angular.module("myApp",[]).controller('akshay',['$scope',
// include controller dependency in case of third type
var app = angular.module('app', ['controller']);
// first type to declare controller
// this doesn't work well
var FirstController = function($scope) {
$scope.val = "First Value";
}
//Second type of declaration
app.controller('FirstController', function($scope) {
$scope.val = "First Controller";
});
// Third and best type
angular.module('controller',[]).controller('FirstController', function($scope) {
$scope.val = "Best Way of Controller";
});

Categories

Resources