How do i navigate one page to another in angularjs - angularjs

i tried to navigate one page to another page but it didn't work.i used angularjs as front end.
My angularjs file is
var app = angular.module('loginApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
// default route
$urlRouterProvider.otherwise("/");
// app routes
$stateProvider
.state('home', {
url: '/tokken/s/',
templateUrl: 'templates/register.html',
controller: 'loginCtrl'
});
});
// Controller function and passing $http service and $scope var.
app.controller('loginCtrl', function($scope, $state, $http) {
// create a blank object to handle form data.
$scope.user = {};
// calling our submit function.
$scope.submitForm = function() {
// Posting data to file
$http.post('/tokken/login/', $scope.user).then(function (response) {
//$httpProvider.defaults.headers.common["X-AUTH-TOKEN"] = response.data;
if (response.errors) {
// Showing errors.
$scope.errorName = response.errors.name;
$scope.erroPassword = response.errors.password;
} else {
//$scope.message = response.data;
$state.go('home');
}
});
};
// calling our submit function.
$scope.regForm = function() {
// Posting data to file
$http.post('/tokken/s/', $scope.user).then(function (response) {
//$httpProvider.defaults.headers.common["X-AUTH-TOKEN"] = response.data;
if (response.errors) {
// Showing errors.
$scope.errorName = response.errors.name;
$scope.erroPassword = response.errors.password;
} else {
$scope.message = response.data;
}
});
};
});
/////////////
My html files is
<!DOCTYPE html>
<html ng-app="loginApp">
<head>
</head>
<body ng-controller="loginCtrl" ui-view="content">
<form ng-submit="submitForm()">
<br> user name:
<input type="text" ng-model="user.name">
<br>
<br> password:
<input type="text" ng-model="user.password">
<br>
<input type="submit" value="login">
</form>
</body>
<script src="/js/angular.min.js"></script>
<script src="/controller/login.js"></script>
<script src="/js/angular-ui-router.min.js"></script>
</html>
above code post a value. but didn't navigate to another page.
while i using $location provider in it. post didn't work. help me please

You should rather put the index contents into another template so that the state can return to "/" if the state changed, and because you set it as the default state: $urlRouterProvider.otherwise("/");
Add this to your stateProvider:
.state('login', {
url: '/',
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
});
Also since your state is already assigning a controller the ng-controller="loginCtrl" in the body tag does not belong there.

Please check this code
.state('home', {
url: '/token/s',
views: {
'content#': {
templateUrl: 'templates/register.html',
controller: 'loginCtrl'
}
}
})
Instead of
.state('home', {
url: '/tokken/s/',
templateUrl: 'templates/register.html',
controller: 'loginCtrl'
});

Related

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;

Angular ui-router resolve http empty value

I'm testing a simple angular application and I'm facing some problems. The http GET call is done but resolver renders empty. Here is the code :
A simple index.html :
<html ng-app="myApp">
<head>
//all scripts loaded
</head>
<body ng-controller="myCtrl">
<p>{{test}}</p>
<a ui-sref="tab1">Show Tab 1</a>
<a ui-sref="tab2">Show Tab 2</a>
<a ui-sref="tab3">Show Tab 3</a>
<ui-view></ui-view>
</body>
</html>
The app.js :
var app = angular.module('myApp', ['ui.router']);
app
.service('DataService', function ($http) {
return {
getData: function() {
return $http({
method : "GET",
url : "/hi"
}).then(function(response) {
return response.data;
},function(response) {
return "error";
});
}
}
});
app
.controller('myCtrl', function($scope) {
$scope.test = "Test";
});
app
.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('tab1', {
url: '/tab1',
templateUrl: '/assets/templates/tab1.html'
})
.state('tab2', {
url: '/tab2',
templateUrl: '/assets/templates/tab2.html'
})
.state('tab3', {
url: '/tab3',
templateUrl: '/assets/templates/tab3.html'
resolve:{
mydata : function (DataService) {
return DataService.getData();
}
},
controller: 'myCtrl'
});
$urlRouterProvider.otherwise('/tab1');
});
Tab3 template :
<p>Data: {{mydata}}</p>
As I said, when I click the "tab3" link, the http get call is done, and a JSON data is retrieved, but "mydata" is rendered to blank.
Any clue??
Thanks and regards.
Your controller doesn't do anything with mydata. So it's not in the scope, so the view can't display it. It should be:
app.controller('myCtrl', function($scope, mydata) {
$scope.mydata = mydata;
});

Using global template variable in controllers angularjs

I am trying to add viewTitle to base view or root web app page, e.g.
Root Page
<div ng-app="app">
{{viewTitle}}
<div ui-view=""></div>
</div>
can I change viewTitle in controllers ?
Controller-1
var myApp = angular.module(app, []);
myApp.controller('ChildController', ['$scope', function($scope) {
// how to update viewTitle here ?
}]);
One solution may be this:
If you use ui-router you can add a title in state: (I use this to translate the title)
.state('login', {
url: '/login',
controller: 'AdminLoginController',
templateUrl: 'app/admin/views/login.html',
title: {
'es': 'Iniciar sesión',
'en': 'Login',
'de': 'Einloggen'
}
})
.state('panelAdmin', {
url: '',
controller: 'AdminHomeController',
templateUrl: 'app/admin/views/panelAdmin.html',
title: {
'es': 'Panel de administración',
'en': 'Control panel',
'de': 'Führungspanel'
}
})
And in $stateChangeStart reload the title:
$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
if (toState.title) {
$rootScope.title = toState.title[$rootScope.cultureLang];
}
});
In index.html:
<title>{{title}}</title>
I think we can use $rootScope for this purpose. Please see below.
html template
<body ng-app="myApp" >
{{viewTitle}}
<div ui-view=""></div>
</div>
</body>
js file
myApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/',
template: '<h1>From nested view </h1>',
controller: function($rootScope)
{
$rootScope.viewTitle = "home";
}
});
});
Hope it helps

Navigation and states inside ionic framework

i'm trying to make an app where the first time you use it I save some information locally. My purpose is that when the next times a person open the app it will be shown another page.
The problem is that I don't know how to load a simple page (not a part like a template) from my controller function.
Here my html
<body ng-app="starter" ng-controller="MainCtrl">
<ion-content class="center" [....]
<button class="button button-calm button-full button-clear button-large" ng-click="saveAll(name, job)">
<span style="font-size: 1.4em;">start</span>
</button>
</ion-content>
</body>
app.js
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state('home', {
url: "/home",
controller: "HomeCtrl",
template: "<h1>Home page</h1>"
})
$urlRouterProvider.otherwise('/first')
})
.controller('MainCtrl', function($scope, $localstorage, $location) {
$scope.setName = function(name) {
if (name) {
$localstorage.set('name', name.toLowerCase());
console.log(name);
}
}
$scope.getName = function() {
alert($localstorage.get('name'));
}
$scope.setJob = function(job) {
if (name) {
$localstorage.set('job', job.toLowerCase());
console.log(job);
}
}
$scope.getJob = function() {
alert($localstorage.get('job'));
}
$scope.saveAll = function(name, job) {
if (name) {
$localstorage.set('name', name.toLowerCase());
console.log(name);
}
if (job) {
$localstorage.set('job', job.toLowerCase());
console.log(job);
}
if (name && job) {
$location.path("home");
}
}
})
You can navigate routes using:
$location.path('/home');
or:
$state.go('home');
So.. in your MainCtrl you could put something like this:
$scope.getName = function() {
return $localstorage.get('name');
};
$scope.getJob = function() {
return $localstorage.get('job');
};
var init = function(){
if($scope.getName() && $scope.getJob()){
$location.path('/home');
}
};
init();
UPDATE:
Ionic has ui-router installed by default. ui-router documentation.
Each route accept a templateUrl property. I don't know which is you folder structure so you need to change them to work correctly:
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
controller: 'HomeCtrl',
templateUrl: 'home/home.html'
})
.state('first', {
url: '/first',
controller: 'FirstCtrl',
templateUrl: 'first/first.html'
})
.state('second', {
url: "/second",
controller: "SecondCtrl",
templateUrl: 'second/second.html'
});
$urlRouterProvider.otherwise('/first');
})

Can't Select Elements After Routing Completed in Angular

I want to validate my form just like this pen. But I'm also using ui-router and my form fields are in another partial page. So I can't select my form as selected as in pen(below).
if ($scope.userForm.$valid) {
alert('our form is amazing');
}
In console I'm getting this error. "TypeError: Cannot read property '$valid' of undefined".
So what should I do for catch my form fields which are come from partials?
By the way theese are my codes
var app = angular.module("App",['ui.router']);
app.controller("Controller", function($scope){
$scope.Go = function(){
alert($scope.name);
if($scope.userForm.$valid){
alert("Valid");
}
else{
alert("No Valid");
}
}
});
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/', {
url: '/',
templateUrl: 'input.html'
})
});
This is my index.html
<div ng-controller="Controller">
<ui-view></ui-view></div>
And this is my partial.html
<form name="userForm">
<input type="text" ng-model="name"/>
<button ng-click="Go()">Go</button></form>
Basically you need to point your form to the parent scope like $parent.userForm & to get access to the form value do initialize form object inside parent controller of ui-view like $scope.form = {}. Then we will place all form level values in it.
HTML
<body ng-controller="Controller">
<ui-view></ui-view>
</body>
CODE
app.controller("Controller", function($scope) {
$scope.form = {};
$scope.Go = function() {
alert($scope.form.name);
if ($scope.userForm.$valid) {
alert("Valid");
} else {
alert("No Valid");
}
}
});
input.html
<form name="$parent.userForm">
<input type="text" ng-model="form.name" />
<button ng-click="Go()">Go</button>
</form>
Working Plunkr
Hope this could help you, Thanks.
You can do what #pankajparkar said. Or you need to modify your state:
$stateProvider
.state('/', {
url: '/',
templateUrl: 'input.html',
controller: 'Controller'
});
and remove the ng-controller="Controller".
UI Router will automatically load the specified controller for that given state and bind it the input.html.

Resources