angularjs controller giving Unknown Provider for $stateParams - angularjs

I am new to angular js, I am creating a test app to understand the flow, however when I am trying to use $stateParams then my controller is not loading, in console I am getting the error message which is redirecting me to https://docs.angularjs.org/error/$injector/unpr?p0= where I am able to see this
Error: error:unpr Unknown Provider
My controller looks like below
angular.module('NerdCtrl', []).controller('NerdController', ["$scope","$stateParams", "Nerd", function($scope, $stateParams, Nerd) {
$scope.getAll = function() {
Nerd.get().success(function(data, res) {
$scope.nerds = data
})
}
$scope.saveNerd = function(nerd){
Nerd.create(nerd).success(function(data, res){
console.log(data)
});
}
$scope.getNerd = function(){
console.log($stateParams.id)
}
}]);
Nerd is a factory which I have created for services
If I am not including $stateParams then everything is working fine as expected.

Related

Testing AngularJS + Jasmine Unexpected request

I created an application using AngularJS which you can only access after logging in.
Now I'm starting to learn how to use Jasmine.
I created a simple test (see below) just to see if everything is ok.
describe('dashboardController', function() {
beforeEach(module('mainModule'));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('demo', function() {
it('demo spec', function() {
var $scope = {};
var controller = $controller('dashboardController', { $scope: $scope });
expect($scope.foo).toEqual(1);
});
});
});
When I load the application I get "finished in 0.011s1 spec, 0 failures" which means the test went just fine.
However it is blocking me from doing anything. I cant click on the login button or anything else. I also get this error in the console:
"Error: Unexpected request: GET api/getUser
No more request expected
at $httpBackend (angular-mocks.js:1232)"
this route above is responsible for checking if the user is logged in or not.
Im new to Jasmine with AngularJS. Can someone clarify what's going on here?
EDIT: Here's my controller:
angular.module("mainModule")
.controller("dashboardController", ["$scope", "$rootScope", function ($scope, $rootScope) {
$scope.foo = 1;
}]);

Ionic Framework Interaction with API

I'm trying to retrieve information from Reddit's JSON API(RedditUrl.json) and show it on my Ionic Creator App. I've bound the HTML and JS by typing {{variable}}, so that's not the problem. In addition to that, I typed Angular Directives on the component I'm working with like:
ng-app = "ionicApp" ng-controller = "MainCtrl"
Actual JS code:
function ($scope, $stateParams) {
console.log('Mert');
angular.module('ionicApp', [])
.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.reddit.com/r/worldnews.json').then(function(resp) {
$scope.title = resp.data.title;
$scope.num_comments = resp.data.num_comments;
$scope.ups = resp.data.ups;
console.log('Mert');
// For JSON responses, resp.data contains the result
}, function(err) {
console.error('Selami');
console.error('ERR', err);
// err.status will contain the status code
})
});
}
I want to parse dynamic data to the app but am getting in the console:
Error: [ng:areq] Argument 'MainCtrl' is not a function, got undefined.
What am I missing here? If I don't write the directives, values are being blank.

Angularjs, global Service throwing error

Stuck in a situation, my app is configured in a way, that I have an app controller, which is using ng-route to route between different views and partials, Now from the login controller, I am making a request to get some data, now I want that data to be accessed globally in the application. Now when I create a service, I am injecting it in the app controller module, but I am getting an error service is not defined,
My app.js:
var myApp = angular.module('app', ['loginMod', 'dashboardMod', 'newRequestMod', 'ngAnimate', 'ui.bootstrap', 'ngRoute', 'userDetailService']);
myApp .config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: 'resources/pages/login.html',
controller:'loginController'
})
...
Now in my logincontroller i am using the service :
userDetailShareService.sendData(loginModel);
console.log("Checking the service if it works " + userDetailShareService.getData);
userDetailShareService.js:
var app = angular.module('userDetailService',[]);
app.factory('userDetailShareService', function($timeout,$rootScope) {
var service = {};
var dataArray = [];
service.data = [];
service.sendData = function(data){
//dataArray.push(data);
dataArray=this.data;
};
service.getData = function(){
return dataArray;
};
return service;
});
No I am not sure what is throwing that error, the app.js is the first page that is hit, and the data mentioned in login controller is some response data, that I am getting in login controller and then I want to share across my entire application, every controller the data that I get, I do not want to use $rootScope as it will burden the same.
Could anybody please reply, I am in a great need. Thanks in advance.

Refused to execute script from '*' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled

I am a newbie to AngularJS. I am using a rails application to expose data in json format. The data is to be used by angular app. The angular repo and the rails repo are completely different. The reason for different repositories is because I want my rails repo just to expose data using APIs which i can use in the angular app.
My rails controller is as below
class Api::V1::PhonesController < ApplicationController
def index
render json: Phone.all
end
def show
render json: Phone.find(params[:id])
end
...
end
Now, when i visit 'localhost:3000/api/v1/phones', it returns me the json data for all the phones. When I visit 'localhost:3000/api/v1/phones/1', it returns the the json data for the phone with id 1. I validated the json data format using http://jsonlint.com/. Everything works fine till here.
My angularjs route file is as:
$routeProvider.
when('/phones', {
templateUrl: 'list.html',
controller: 'PhoneListController'
}).
when('/phones/:id', {
templateUrl: 'show.html',
controller: 'PhoneShowController'
}).
otherwise({
redirectTo: '/phones'
});
}]);
My index.html in the angular repo has the list.html template embedded in it.
<html ng-app='phoneCatApp'>
...
</html>
<script type="text/ng-template" id="list.html">
This is the list template.
</script>
the code for the services.js is as:
var appServices = angular.module('appServices', []);
phoneCatApp.factory('appServices', ['$http', '$q', function($http, $q){
var url = "http://localhost:3000/api/v1/";
//get all phones
this.getPhones = function(){
var defered = $q.defer();
var listApi = url + "phones";
$http.jsonp(listApi).then(function(results){
defered.resolve(results);
}, function(error){
defered.reject(error);
});
return defered.promise;
}
return this;
}]);
The text in the script template is displayed as well when I visit '#/phones'. The problem is that
1) In chrome, following error is displayed when i inspect the page.
Refused to execute script from 'http://localhost:3000/api/v1/phones' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.
2) in firefox, the following error is getting displayed.
SyntaxError: missing ; before statement
Thanks for the help.
Hey so I believe your problem is that your rails controller is returning JSON and NOT JSONP. Your controller has to explicitly specify a callback function, which can be specified by the request params.
See Handling jsonp in rails 3 controller for an example of returning JSONP from a rails controller
So your rails code would look like (argh my rails is very very rusty...):
class Api::V1::PhonesController < ApplicationController
def index
if params[:callback]
format.js { render :json => {:phones => Phone.all.to_json}, :callback => params[:callback] }
else
format.json { render json: {:phones => Phone.all.to_json}}
end
end
Then for the angular side, this answer should help you out:
parsing JSONP $http.jsonp() response in angular.js
And I think your angular would then look like:
var appServices = angular.module('appServices', []);
phoneCatApp.factory('appServices', ['$http', '$q', function($http, $q){
var url = "http://localhost:3000/api/v1/";
//get all phones
this.getPhones = function(){
var defered = $q.defer();
var listApi = url + "phones?callback=JSON_CALLBACK";
$http.jsonp(listApi).then(function(results){
defered.resolve(results);
}, function(error){
defered.reject(error);
});
return defered.promise;
}
return this;
}]);

Wire up AngularJS controller to express controller

I'm getting started with node/express/Angular by using the MEAN stack at mean.io.
I don't understand how the Angular controller calls the express controller to fetch data.
What I have is public/js/controllers/index.js:
angular.module('mean.system').controller('IndexController', ['$scope', 'Global', 'Tabs',
function ($scope, Global, Tabs) {
$scope.global = Global;
Tabs.query(function(tabs) {
$scope.tabs = tabs;
});
}]);
But I'm confused what exactly 'Tabs' is. I know that somehow, magically, eventually this method is called - I think this is the Express controller?
app/controllers/tabs.js:
exports.all = function(req, res) {
Tab.find().sort('artist').select("-content").populate('user').exec(function(err, tabs) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(tabs);
}
});
};
But I don't understand how it gets called. What I want to do is call a different method in app/controllers/tabs.js instead - namely, this:
exports.newest = function(req, res) {
Tab.find().sort('-created').limit(10).select("-content").exec(function(err, tabs) {
...
But I don't understand how to "wire up" the AngularJS controller with the express controller.
i.e. what do I have to do so that I can do something like this in my controller:
angular.module('mean.system').controller('IndexController', ['$scope', 'Global', 'Tabs',
function ($scope, Global, Tabs) {
$scope.global = Global;
Tabs.newest(function(tabs) { // this won't work
$scope.tabs = tabs;
});
}]);
In MEAN, The Articles service is an angular service that returns a $resource object you can usually find in the public/js/services folder.
$resource is a wrapper around $http AJAX service that comes with angularjs, it enables you to connect with RESTful endpoints if your REST service is built in a specific manner.
The connection to the the node.js controller happens using the routes.js object found in the config folder that binds routes to specific module methods.
further reading:
http://docs.angularjs.org/api/ngResource.$resource
http://expressjs.com/api.html#app.VERB

Resources