Angular could not find my controller - javascript

In my app I'm trying to pass the Id value to my controller like this:
http://localhost:29045/visitorMain/?Id=afef8e80-0864-e411-8865-000c295e296b
But I am getting a "The resource cannot be found" error.
Here is my code below:
app.js
'use strict';
var app = angular.module('loginApp', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.when('/login', {
templateUrl: 'partials/login.html',
controller: 'loginController'
});
$routeProvider.when('/visitorMain/:Id', {
templateUrl: 'partials/visitorMain.html',
controller: 'visitorController'
});
$routeProvider.otherwise({
redirectTo: '/login'
});
}
]);
visitorController.js
'use strict';
app.controller('visitorController', function($scope, $routeParams) {
//console.log(Id);
//console.log(UserName);
// $scope.login = function (user) {
// loginService.login(user);
// }
});
Calling My visitorController
$http.get('/visitorMain/', {
params: {
Id: "someid"
}
});
Result:
Any suggestions?

You are forgetting the hashtag. Try
$http.get('/#/visitorMain/', {
params: {
Id: "someid"
}
});

You have uncorrect url. Your controller should be like this:
$http.get('/visitorMain', {
params: {
Id: "someid"
}
});
So your url will be: http://localhost:29045/visitorMain?Id=afef8e80-0864-e411-8865-000c295e296b.

Related

state params not getting in other state

I have a scenario where when I click on a link i need to change the route and also add send some params to the other state.
The issue here is the params are empty when I console it in other state
<div ng-repeat="items in vm.Items">
<a ng-click="vm.goToDetails(items.id)">{{items.title}}</a>
</div>
Controller:
vm.goToDetails = function(Id) {
$state.go('Details', {
'fid': Id
});
}
route:
$stateProvider.state('Details', {
url: '/details/:fid',
resolve: {
selectedProduct: ['$state', '$stateParams',
function($state, $stateParams) {
console.log($stateParams.fid) //getting empty string here
console.log($state.params.fid)//getting undefined here
}
]
}
});
Any help would be appreciated.
You need to specify the parameters name in the route url:
/some-route/:fid
I didn't find any issue with the code, may be the issue is with the injection of resolved parameter.
I created a DEMO with your code. This may be helpful to you.
Here is config,
app.config(function($stateProvider,$urlRouterProvider){
$stateProvider.state('Details', {
url: '/details/:fid',
templateUrl: 'detail.html',
controller: 'DetailController',
resolve: {
selectedProduct: ['$state', '$stateParams',
function($state, $stateParams) {
console.log($stateParams.fid) //getting empty string here
alert($stateParams.fid) //getting empty string here
return $stateParams.fid
}
]
}
});
$stateProvider.state('login',{
url: '/login',
templateUrl: 'login.html',
controller: 'LoginController'
});
$urlRouterProvider.otherwise('/login');
});
Controller that contains repeated object,
app.controller('LoginController',function($scope,$state){
$scope.Items = [{id: 1,title: "Title1"},{id: 2,title: "Title2"},{id: 3,title: "Title3"}]
$scope.goToDetails = function(Id) {
console.log(Id)
$state.go('Details', {
'fid': Id
});
}
})
This is the controller where you can inject selectedProduct
app.controller('DetailController',function($scope,$state,selectedProduct){
$scope.selectedProduct = selectedProduct;
})
PLEASE CHECK THIS DEMO

how to remove exclamation from routing of state url Mean full stack

I want to remove exclamation marks from url state routing like my url is now http://localhost:3000/#!/auth/register
i just want to remove this "!" marks from url after "#"
Is it possible to do? with mean.io
here is my app.js/system.js
'use strict';
//Setting up route
angular.module('mean').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// For unmatched routes:
//$urlRouterProvider.otherwise('/');
var checkLoggedin = function($q, $timeout, $http, $location) {
// Initialize a new promise
var deferred = $q.defer();
// Make an AJAX call to check if the user is logged in
$http.get('/loggedin').success(function(user) {
// Authenticated
if (user !== '0') $timeout(deferred.resolve);
// Not Authenticated
else {
$timeout(deferred.reject);
$location.url('/auth/login');
}
});
return deferred.promise;
};
// console.log($stateProvider);
// states for my app
$stateProvider
.state('tasks', {
url: '/kanban/:projectId/:projectSlug',
templateUrl: 'system/views/index.html',
controller: 'IndexController',
resolve: {
loggedin: checkLoggedin,
onEnter: function($stateParams,$state, $uibModal) {
if ( $stateParams.projectId != "" ) {
updateTopMenu('Kanban','task','#!/kanban/'+$stateParams.projectId+'/'+$stateParams.projectSlug);
updateTopMenu('Schedule','schedule','#!/schedule');
}
}
}
}).state('home',{
url:'/',
templateUrl: 'projects/views/index.html',
controller: 'ProjectController',
resolve:{
loggedin: checkLoggedin
}
}).state('taskEdit',{
url:'/kanban/:projectId/:projectSlug/:taskSlug',
templateUrl: 'system/views/index.html',
controller: 'IndexController',
resolve:{
loggedin: checkLoggedin
}
}).state('taskAdd',{
url: "/task/taskAdd",
onEnter: function($stateParams, $state, $uibModal) {
$uibModal.open({
templateUrl: "system/views/include/model.html",
resolve: {},
controller: function($scope, $state, itemService) {
/*
$scope.state = $state.current;
$scope.params = $stateParams;
$scope.item = itemService.get($stateParams.id);
*/
$scope.ok = function () {
$scope.$close('clicked ok');
};
$scope.dismiss = function () {
$scope.$dismiss('clicked cancel');
};
}
}).result.then(function (result) {
// $scope.$close
alert('result ->' + result);
}, function (result) {
// $scope.$dismiss
return $state.transitionTo("home");
alert('dismiss ->' + result);
}).finally(function () {
// handle finally
return $state.transitionTo("tasks");
});
}
});
}
]).config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
you have configured it here
function($locationProvider) {
$locationProvider.hashPrefix('!');
}
remove this line to get ! removed from url
or enable html5mode using below code to remove # from url
$locationProvider.html5Mode(true);
but please read more about how url routes are handled in angular, and server side routing vs client side routing etc, before enabling html5mode
Change $locationProvider.hashPrefix('!'); to $locationProvider.hashPrefix('');
System.js
.config(['$locationProvider',
function($locationProvider) {
$locationProvider.hashPrefix('');
}
]);

Unexpected identifier while adding controller to ngRoute

I've faced with such problem, when I add controller to my route code it fails to unexpected identifier. Have no idea why it's happening
This is my routeProvider:
app.config(function($routeProvider) {
$routeProvider
.when("/login", {
title: 'Login',
templateUrl: 'assets/login.html'
controller: authCtrl
})
});
And this is my controller:
app.controller('authCtrl', function ($scope, $rootScope, $routeParams, $location, $http, Data) {
//initially set those objects to null to avoid undefined error
$scope.login = {};
$scope.signup = {};
$scope.doLogin = function (customer) {
Data.post('login', {
customer: customer
}).then(function (results) {
Data.toast(results);
if (results.status == "success") {
$location.path('dashboard');
}
});
};
$scope.signup = {email:'',password:'',name:'',phone:'',address:''};
$scope.signUp = function (customer) {
Data.post('signUp', {
customer: customer
}).then(function (results) {
Data.toast(results);
if (results.status == "success") {
$location.path('dashboard');
}
});
};
$scope.logout = function () {
Data.get('logout').then(function (results) {
Data.toast(results);
$location.path('login');
});
}
});
I've included such paths in my html:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"/>
<script src="app/angular-route.min.js"></script>
<script src="app/angular-animate.min.js" ></script>
<script src="app/toaster.js"></script>
<script src="app/app.js"></script>
There is some typos in your code :
app.config(function($routeProvider) {
$routeProvider
.when("/login", {
title: 'Login',
templateUrl: 'assets/login.html', // <---- missing ','
controller: 'authCtrl' // <----- should be format to string
})
});
Not sure if it will solve your problem
try it.
app.config(function($routeProvider) {
$routeProvider
.when("/login", {
title: 'Login',
templateUrl: 'assets/login.html',
controller: 'authCtrl' // <-- string
})
});
the controller name must pass as a string..try this
app.config(function($routeProvider) {
$routeProvider
.when("/login", {
title: 'Login',
templateUrl: 'assets/login.html',
controller: 'authCtrl'
})
});

How to manage factory single request data in a state with some ui views

Being pretty new at AngularJS, I'm trying to understand how to manage a single JSON that is comming from a single $http.get request which is gonna be used by 2 different controllers in 2 diferent ui-view.
The idea is to show the data of the user in the first ui-view and the data of the story in the second one.
Right now my factory do 2 $http requests, due to it's called twice by the two controllers.
Right now what I have is what it follows:
homeFactory.js
var homeFactory = angular.module('home.factory', []);
homeFactory.factory('homeData', [ '$http', '$q', function ($http, $q) {
var endpoints = null;
return {
getStories: function(url) {
return endpoints ?
$q(function(resolve, reject) { resolve(endpoints); }) :
$http.get(url + '/main/get', {
transformRequest : angular.identity,
headers : {'Content-Type' : undefined}
}).then(function(data) { endpoints = data; return data; });
}
};
}]);
home.js
var home = angular.module('home', ['home.factory']);
home.controller('topbarCtrl', [ 'CONFIG', 'homeData', function(CONFIG, homeData) {
var data = this;
data.stories = {};
homeData.getStories(CONFIG.API_URL).then(function(response) {
data.stories = response.data.stories;
}, function(error) {
console.log("Failed to load end-points list");
});
}]);
home.controller('contentCtrl', [ 'CONFIG', 'homeData', function(CONFIG, homeData) {
var data = this;
data.stories = {};
homeData.getStories(CONFIG.API_URL).then(function(response) {
data.stories = response.data.stories;
}, function(error) {
console.log("Failed to load end-points list");
});
}]);
app.js
(function () {
var app = angular.module('init', [
'home', 'ui.router'
]);
app.run([
'$rootScope',
'$state',
'$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]);
app.constant('CONFIG', {
'API_URL': 'https://xxxxxxxxx/',
'S3_PATH': 'http://resources.xxxxxxxxx.com',
'CLOUDFRONT': 'http://resources.xxxxxxxxx.com'
});
app.config([
'$stateProvider',
'$urlRouterProvider',
'$locationProvider',
'$sceDelegateProvider',
function ($stateProvider, $urlRouterProvider, $locationProvider, $sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'http://resources.xxxxxxxxx.com/**'
]);
$urlRouterProvider
.when('/logout', '/')
.otherwise('login');
$stateProvider
.state('home', {
url: "/home",
views: {
'header': { templateUrl: "app/Home/_topbar.html" },
'content': { templateUrl: "app/Home/_home.html" },
'footer': { templateUrl: "app/Home/_navbar.html" }
}
});
}
]);
}());
index.html
<!DOCTYPE html>
<html lang="en" ng-app='init'>
<head>
<meta charset="utf-8">
<script src="js/angular.min.js"></script>
<script src="js/angular-ui-router.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
<script src="app/app.js"></script>
</head>
<body>
<script src="app/Home/home.js"></script>
<script src="app/Home/HomeFactory.js"></script>
<div ui-view="main">
<div ui-view="header"></div>
<div class="wrapper" ui-view="content"></div>
<nav ui-view="footer"></nav>
</div>
<script src="js/sha512.js"></script>
</body>
</html>
How could I achieve what I need?
Thanks in advice.
UPDATE
The solution I applied is on the main controller is to request the data via resolve directive and asign a controller to each view as it follows:
$stateProvider
.state('home', {
url: "/home",
resolve: {
response: [ 'CONFIG', '$http', function(CONFIG, $http) {
return $http.get(CONFIG.API_URL + '/home').then(function(response) {
return response.data;
});
}]
},
views: {
'header': { templateUrl: "app/Home/_topbar.html", controller: 'headerCtrl', controllerAs: 'my' },
'content': { templateUrl: "app/Home/_home.html", controller: 'contentCtrl', controllerAs: 'my' },
'footer': { templateUrl: "app/Home/_navbar.html", controller: 'footerCtrl', controllerAs: 'my' }
}
});
Then you don't need to declare ng-controller to the html view.
You can use ui-router's resolve to make the api call and inject the resolved data into the controller.
app.js
$stateProvider
.state('home', {
url: "/home",
resolve: {
response: ['homeData', '$q', 'CONFIG', function(homeData, $q, CONFIG) {
var deferredData = $q.defer();
homeData.getStories(CONFIG.API_URL).then(function(response) {
return deferredData.resolve({
data: response.data
});
})
return deferredData.promise;
}]
}
views: {
'header': { templateUrl: "app/Home/_topbar.html" },
'content': { templateUrl: "app/Home/_home.html" },
'footer': { templateUrl: "app/Home/_navbar.html" }
}
});
Controller:
home.controller('topbarCtrl', ['response', function(response) {
console.log(response.data) //this will contain the response data
}]);
home.controller('contentCtrl', ['response', function(response) {
console.log(response.data) //this will contain the response data
}]);

Creating a custom provider angularjs

I am trying to create some routing that will resolve calls to my rest api
before the page loads. Because I can't inject a service created using
app.factory(), I am attempting to create a provider to do this so I can use it in my config routing, but I'm
getting Error: [$injector:unpr] Unknown provider: $http
I want to be able to call the provider in mainFlow.api for 4 or five endpoints
that will resolve before the page loads. Am I going about this the correct way?
My code:
service.js
var mainApp = angular.module('mainApp');
mainApp.provider('choiceService', ['$http', function($http) {
return {
$get: function() {
return {
get: function(url) {
return $http.get(url);
}
};
}
};
}]);
config.js
var mainApp = angular.module('mainApp', [
'ui.router'
]);
mainApp.config(['$stateProvider', '$urlRouterProvider', '$choiceServiceProvider',
function($stateProvider, $urlRouterProvider, choiceServiceProvider) {
$stateProvider
.state('mainFlow', {
abstract: true,
url: '/base',
template: '<ui-view/>'
})
.state('mainFlow.choose-main', {
url: '',
templateUrl: '/choose_main.html',
})
.state('mainFlow.contact', {
controller: 'ContactFormController',
url: '/contact-details',
templateUrl: '/panel_contact_info.html',
})
.state('mainFlow.api', {
url: '/about-your-api',
controller: 'ApiFormController',
templateUrl: '/panel_about_your_api.html',
resolve: {
choice: function(choiceServiceProvider) {
return choiceServiceProvider.get('/api/yes-no-choice/');
},
other_choice: function(choiceServiceProvider){
return choiceServiceProvider.get('/api/my-other-choice/')
}
}
})
Then I can use the resolved data in controller.js
controller.js
var mainApp = angular.module('mainApp');
mainApp.controller('ApiFormController', [
'$scope',
'$state',
'choiceService',
function($scope, $state, choiceService) {
$scope.choices = choiceService;
}
]);
I was passing $http in service.js when there was no need. I was also passing in '$choiceServiceProvider' in config.js when it should have been just 'choiceServiceProvider'

Categories