UI-Router don't route with param - angularjs

I use UI-Router. I have a first controller
vehicuels.controller.js:
'use strict';
angular.module('autoPrivilegeApp')
.controller('VehiculesCtrl', function ($scope,$http, $state) {
$scope.awesomeThings = [];
$http.get('/api/cars').success(function (awesomeThings) {
$scope.message = awesomeThings;
});
// Show Car detail
$scope.showCarDetail = function (_id) {
$state.go('vehiculeDetail', {id: _id});
};
});
vehicules.js:
'use strict';
angular.module('autoPrivilegeApp')
.config(function ($stateProvider) {
$stateProvider
.state('vehicules', {
url: '/vehicules',
templateUrl: 'app/vehicules/vehicules.html',
controller: 'VehiculesCtrl'
});
});
vehicules.html:
<div class="col-md-12">
<div ng-repeat="car in message">
<button class="medium bouton bleu" ng-click="showCarDetail(car._id);">
{{ car._id }}
</button>
<br/><br/><br/><br/>
</div>
</div>
I want to pass id to my second controller
vehiculeDetail.controller.js:
'use strict';
angular.module('autoPrivilegeApp')
.controller('VehiculeDetailCtrl', function ($scope,$stateParams ) {
$scope.message = $stateParams.instanceID;
});
vehiculeDetails.js:
'use strict';
angular.module('autoPrivilegeApp')
.config(function ($stateProvider) {
$stateProvider
.state('vehiculeDetail', {
url: '/vehiculeDetail/{id}',
templateUrl: 'app/vehiculeDetail/vehiculeDetail.html',
controller: 'VehiculeDetailCtrl'
});
});
vehiculeDetail.html:
<div class="col-md-12">
This is the vehiculeDetail id {{message}}.
</div>
I have use the yeoman generator --> generator-angular-fullstack
my problem is that I do not get my id in my controller VehiculeDetailCtrl.
What is wrong?

The $stateParams uses name as they are defined in url:
$stateProvider
.state('vehiculeDetail', {
url: '/vehiculeDetail/{id}', // here we name our param as 'id'
So, we have to use now the name id instead of the instanceID
.controller('VehiculeDetailCtrl', function ($scope,$stateParams ) {
//$scope.message = $stateParams.instanceID;
$scope.message = $stateParams.id;

Related

Unknown provider: DashboardServiceProvider <- DashboardService <- DashboardController

even if I read a lot of solutions according my problem, still to have this Error.
This is my Controller:
#Controller
#RequestMapping( "/dashboard" )
public class DashboardController {
#RequestMapping( value = "", method = RequestMethod.GET )
public HttpEntity<String> dashboard() {
SimpleDateFormat sdf = new SimpleDateFormat( "dd-MM-yyyy" );
return new HttpEntity<String>( "Today is " + sdf.format( new Date() ) );
}
}
this is my index.jsp
<body ng-app="dashboard">
<div ng-controller="DashboardController">
<p>Nome: <input type="text" ng-model="nome"></p>
<p>Cognome: <input type="text" ng-model="cognome"></p>
<input type="button" value="LOGIN" ng-click="login()"/>
</div>
<jsp:include page="includes.jsp"></jsp:include>
<div ng-show="value==1">
{{data}}
</div>
<div ng-show="value==0">
{{ResponseDetails}}
</div>
</body>
this is my module
var Dashboard = angular.module( 'dashboard', ['DashboardService'] )
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/dashboard', {
templateUrl: '/WEB-INF/pages/dashboard.jsp',
controller: 'DashboardController'
});
}]);
my service
Dashboard.factory('DashboardService', function ($http) {
return {
dashboard: function(successCallback, errorCallback) {
$http.get("/dashboard")
.success(
function (response) {
$scope.data = response;
}
).error(
function (response) {
$scope.data = "ERROR!";
}
)
}
}
});
and finally my controller
angular.module("dashboard", [])
.controller( 'DashboardController', function ($scope, DashboardService) {
$scope.nome = "Daniele";
$scope.cognome = "Comandini";
var data = {
nome: $scope.nome,
cognome: $scope.cognome
};
$scope.value = 0;
var login = function() {
alert("LOGIN ON DASHBOARD");
DashboardService.dashboard();
};
$scope.login = login;
});
My JSP page must only send the request to the DashBoardcontroller, that it has the return the page dashboard.jsp with the current date.
You must not inject dependencies in your module. Dependencies like service, factory have to be injected in controllers. By the way, don't forget to inject ngRoute.
Module becomes:
var Dashboard = angular.module( 'dashboard', ['ngRoute'] )
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/dashboard', {
templateUrl: '/WEB-INF/pages/dashboard.jsp',
controller: 'DashboardController'
});
}]);
Your controller code is good, just one thing: if you want to use a code compiler like Grunt, Gulp or Webpack, don't forget to add your dependencies as strings:
angular.module('dashboard')
.controller( 'DashboardController', ['$scope', 'DashboardService'], function ($scope, DashboardService) {
I copied your controller with the service injection
.controller( 'DashboardController', ['$scope', 'DashboardService'], function ($scope, DashboardService) {
but in the end I had to write this
Dashboard.controller( 'DashboardController', ['$scope', 'DashboardService' , function ($scope, DashboardService) {
$scope.nome = "Daniele";
$scope.cognome = "Comandini";
var data = {
nome: $scope.nome,
cognome: $scope.cognome
};
$scope.value = 0;
var login = function() {
alert("LOGIN ON DASHBOARD");
DashboardService.dashboard();
};
$scope.login = login;
}]);
I mean I had to include the function into [], and not outside.

AngularJS router - parent controller loads when child is clicked

I am having strange results working with AngualarJS states. Here is app code:
/* myApp module */
var myApp = angular.module('myApp', ['ui.router'])
.config(function ($stateProvider) {
$stateProvider.state('home', {
url: "home",
template: '<div ui-view><h3>Home</h3><a ui-sref="home.child({reportID:1})">Child</a></div>',
params: { reportID: null },
controller: function ($scope) {
$scope.homeCtrlVar = "home";
console.log("Home controller loaded");
}
}).state('home.child', {
template: '<div><h3>Child</h3><a ui-sref="home">Back</a></div>',
controller: function ($scope) {
$scope.childCtrlVar = "child";
console.log("Child controller loaded");
}
});
})
.controller('MainCtrl', function ($scope, $state) {
console.log("MainCtrl initialized!");
$state.go("home");
});
And main page:
<div ng-app="myApp" ng-controller="MainCtrl">
<h2>My app</h2>
<div ui-view></div>
What's happening is that as long as there parameters for the home state and reportID value doesn't match between a parameter being sent and the state default the home controller is loaded when I click on Child. Can someone please explain why that's happening?
Fiddle
Here is updated code which works as you expect it to:
var myApp = angular.module('myApp', ['ui.router'])
.config(function ($stateProvider) {
$stateProvider.state('home', {
url: "home",
template: '<div ui-view><h3>Home</h3><a ui-sref="home.child({reportID:1})">Child</a></div>',
controller: function ($scope) {
$scope.homeCtrlVar = "home";
console.log("Home controller loaded");
}
}).state('home.child', {
url: "/:reportID",
params: { reportID: null },
template: '<div><h3>Child</h3><a ui-sref="home">Back</a></div>',
controller: function ($scope) {
$scope.childCtrlVar = "child";
console.log("Child controller loaded");
}
});
})
Problem with your approach:
specifying params reportID in home state instead of home.child state.
When user clicks on home.child({ reportId: 1}) it should load home.child, which is fine, and was working with old approach.
However, If you take notice, as you click on home.child({ reportId: 1}), you are sending new parameter reportID(old value was null). reportID belongs to home state, hence its controller is also loaded.
Note that url: "/:reportID" in state home.child is optional.

status undefined when try to fetch data on json and place it on single page of each data

heres my code, i try to show my selected product form my product page by id.
for example when i click a product it go to right url like /#/product/2 and it show all the attribute of product id:2. please take a look this code
app.js
angular
.module('app', [
'ui.router',
'app.directives.productCard'
])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/pages/home.html',
controller: 'homeCtrl'
})
.state('product', {
url: '/product',
templateUrl: 'templates/pages/product.html',
controller: 'productCtrl'
})
.state('productDetails', {
url: '/product/:id',
templateUrl: 'templates/pages/productDetails.html',
controller: 'productDetailsCtrl'
})
}])
my services
angular
.module('app')
.factory('Product', ['$http', function($http) {
return {
get: function() {
return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response) {
return response.data;
});
}
};
}])
productCtrl
angular
.module('app')
.controller('productCtrl',['$scope', 'Product', function($scope,Product) {
$scope.title="List Product";
Product.get().then(function(data) {
$scope.products = data;
});
$scope.products=Product.get();
}]);
productdetailsCtrl
angular
.module('app')
.controller('productDetailsCtrl',['$scope','$stateParams', 'Product', function($scope,$stateParams,Product){
$scope.id=$stateParams.id;
Product.get().then(function(data) {
var singleProduct = data.filter(function(entry){
return entry.id === $scope.id;
})[0];
console.log(singleProduct);
console.log($stateParams);
});
}]);
product.html
<div class="col-lg-3 col-md-4 col-sm-6">
<div class="card">
<img class="card-img-top" ng-src="{{item.image}}" alt="{{item.name}}">
<div class="card-block">
<strong class="card-title">{{item.name}}</strong>
</div>
<div class="card-block">
Buy
</div>
</div>
</div>
product detail.html
<p>{{id}}</p>
<p>{{name}}</p>
<p>{{image}}</p>
after all this code,when i try to check via console. i get Object {id: "2"}, but when i try to show all the attribute from product 2 i get on console undefined. why i got undifined. yeah i didnt use and local server. but if its the problem. does all the code is right to print all the attribut of product 2
here the link of the json https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json
Change product details state url to make id parameter as a int which will allow you to pass return entry.id === $scope.id;(strict equality check).Here you have id value as string which makes singleProduct as undefined.
.state('productDetails', {
url: '/product/{id:int}',
templateUrl: 'templates/pages/productDetails.html',
controller: 'productDetailsCtrl'
})
otherwise you have to change your strict check to return entry.id == $scope.id;

Function not getting called using ng-click

Inside the controller I have a login() function which should be called using ng-click like this:
<body ng-app="angularoauthexampleApp">
<div class="social-buttons">
<i class="fa fa-facebook"></i> Facebook
<i class="fa fa-google" ng-click="login()"></i> Google
</div>
</body>
MainJS:
angular.module('angularoauthexampleApp', [
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/afterlogin', {
templateUrl: 'views/afterlogin.html',
controller: 'AboutCtrl'
})
.when('/access_token=:accessToken', {
template: '',
controller: function ($location, $rootScope) {
var hash = $location.path().substr(1);
var splitted = hash.split('&');
var params = {};
for (var i = 0; i < splitted.length; i++) {
var param = splitted[i].split('=');
var key = param[0];
var value = param[1];
params[key] = value;
$rootScope.accesstoken = params;
}
$location.path("/afterlogin");
}
})
.otherwise({
redirectTo: '/'
});
});
Controller:
angular.module('angularoauthexampleApp')
.controller('MainCtrl', ['$scope', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.login=function() {
alert("main");
var client_id="343625411797-hcm0impil8l1mughb8ma2jj966um05bp.apps.googleusercontent.com";
var scope="email";
var redirect_uri="http://localhost:9046/RTH_Sample4/app/";
var response_type="token";
var url="https://accounts.google.com/o/oauth2/auth?scope="+scope+"&client_id="+client_id+"&redirect_uri="+redirect_uri+
"&response_type="+response_type;
window.location.replace(url);
};
}]);
Nothing happens when I click the button on the form or event is not getting fired. I can't see anything wrong with code but some how its not working
MainCtrl gets loaded inside the views/main.html
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
this has to be loaded inside a ng-view directive in your root html.
Inside that html you can use the login().
Another way is to directly use the controller in the root html:
<body ng-app="angularoauthexampleApp">
<div class="social-buttons" ng-controller="MainCtrl">
<i class="fa fa-facebook"></i> Facebook
<i class="fa fa-google" ng-click="login()"></i> Google
</div>
</body>
Also, you have attached ng-click to the i element so you have to click the G icon for login() to work. Move it to the a element and you should be ok.

Delay of scope's update after controller's resolve

I'm downloading some data using firebase before presenting new controller's view, but the template "blinks" before showing the data. I have no idea why, it should show the data instantly without any delay. I've recorded it and marked each individual frame (http://i.imgur.com/pUsMCqX.gif). Console logs the data that resolve object returns. You can see that when data is being logged, the template is being shown with no data at frames 2 and 3.
Template:
<div ng-cloak class="wrapper select-character">
<div>
<div>
<h1>Select character</h1>
<div>
<button ng-click="createNewCharacter()">create new character</button>
</div>
characters' list
</div>
</div>
<div ng-repeat="character in characters">
<div>
Name: {{ character.name }}
<br>
Level: {{ character.level }}
<br>
<button ng-click="enterWorld(character.name)">Choose</button>
</div>
</div>
</div>
Controller:
'use strict';
angular.module('App')
.controller('SelectCharacterCtrl', function($scope, $firebaseSimpleLogin, $location, characters) {
$scope.createNewCharacter = function() {
$location.path("/create-character");
};
$scope.enterWorld = function(name) {
alert(name);
};
$scope.characters = characters;
});
App:
'use strict';
angular.module('App', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'firebase',
'angularfire.firebase',
'angularfire.login'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/log-in.html',
controller: 'LogInCtrl'
})
.when('/select-character', {
templateUrl: 'views/select-character.html',
controller: 'SelectCharacterCtrl',
resolve: {
characters: function($q, $timeout, $firebase, $firebaseSimpleLogin) {
var deferred = $q.defer();
var loginObj = $firebaseSimpleLogin(new Firebase("https://<id>.firebaseio.com"));
loginObj.$getCurrentUser()
.then(function(user) { // get login data
var userSync = $firebase(new Firebase('https://<id>.firebaseio.com/users/' + user.uid));
return userSync.$asObject().$loaded();
})
.then(function(user) { // get all characters
var promises = [];
angular.forEach(user.characters, function(name) {
var promise = $firebase(new Firebase('https://<id>.firebaseio.com/characters/' + name));
promises.push(promise.$asObject());
});
$q.all(promises).then(function(sth) {
console.log(sth);
deferred.resolve(sth);
});
});
return deferred.promise;
}
}
})
.when('/create-character', {
templateUrl: 'views/create-character.html',
controller: 'CreateCharacterCtrl'
})
});
Why does the template "blinks" with no data for 2 frames before updating the scope? Any ideas?
Since $asObject does not return a promise, your list of promises are immediately resolved (instead of after all the data is downloaded). Change your list to return promises too:
angular.forEach(user.characters, function(name) {
var promise = $firebase(new Firebase('https://<id>.firebaseio.com/characters/' + name));
promises.push(promise.$asObject().$loaded());
});

Resources