Angularjs to pass multiple params - angularjs

I want to update status information for which I need to pass two params one is say school_id and other one is status which may be(approved, pending , declined) depending on the user clicks the button. I have a table like school_info with fields like id school_name status So in my applicationjs I need to pass two params id and status. here is my html code, I have ng-repeat so I am using school in schools.
<button class="btn btn-success" ng-model="approve">Approve</button>
<a href="#/changeStatus/{{school.id}}/declined"><button class="btn btn-danger" ng-model="decline">Decline</button><a>
<button class="btn btn-deafult" ng-model="Pending">Pending</button>
my app.js code is
var app=angular.module("admin",[]);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.php',
controller: 'adminCtrl'
}).when('/changeStatus/:id/:sts',{
templateUrl:'home.php',
controller:'adminCtrl'
}).when('/Mapview/:id',{
templateUrl:'mapview.html',
controller:'MapCtrl'
}).otherwise({
redirectTo: "/"
});
});
app.controller("adminCtrl",function($scope,$http,$routeParams){
var sts=$routeParams.status;
var id=$routeParams.id;
console.log("sts"+sts+id);
//here I want two params to be fetched inside console log. when clicked on specific btn.I have seen previous questions asked on multiple params passing but there must be easy way out to get multiple params.
});

Please use ng-href instead of href
and your hrefs should be like as below, no need of :
<a ng-href="#/changeStatus/{{school.id}}/approved"><button class="bt......
<a ng-href="#/changeStatus/{{school.id}}/declined"><button class="btn btn...
then in the controller,
var sts=$routeParams.sts; // u need to get as sts ,
//because you get it as sts in .when('/changeStatus/:id/:sts'..
var id=$routeParams.id;
console.log("sts"+sts);
console.log("id"+id);

Your links are not correct.
In AngularJS docs, they have this example:
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
//
// Then
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
I didnt test it, but I think the only change you need to do is to remove the double-dots from your links, like this:
<a href="#/changeStatus/{{school.id}}/approved">
<button class="btn btn-success" ng-model="approve">Approve</button>
</a>
And also, you have a mistake in your controller. You named the params 'id' and 'sts', but then you use 'id' and 'status'.

Related

unable to fetch data after redirecting to next page

I am redirecting to edit page after clicking on edit button.
<button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" ng-click="editData(n.id.userId)"><span class="glyphicon glyphicon-pencil"></span></button>
On click on this button following code is working.
$scope.editData = function (data, $window) {
console.log(data);
window.location = 'update-data?id=' + data;
}
Now I am redirected to www/xxx/update-data?id=1 url.
From there I want to fetch user data for id=1 and want to show at page.
How to achieve this?
You can parse the url and get id and write code to get the data for the corresponding id inside ngOninit ()
You can fetch the Url using $window and do one of the following based on your requirement
var url = "www/xxx/update-data?id=1";
var id = url.substring(url.indexOf('=')+1);
console.log(id);
var url = "www/xxx/update-data?id=1";
var id = url.substring(url.indexOf('?')+1);
console.log(id);
But the best option (angular way of doing things) will be to do routing and use $routeParams or $stateparams based on your router.
Relevant Links:
Configure Routes and Views using $routeProvider
Documentation ngRoute
UI-Router for AngularJS (1.x)
Get Current URL

AngularJS redirect to view on button click

I'm trying to load a new view when a button is clicked. For some reason it isn't working with one of my paths. It will work with the path /lookup and will go to the lookup page, but when I change the path to /search it does nothing? I'm confused.
Here is my controller:
(function () {
'use strict'
angular
.module('crm.ma')
.controller('navbarCtrl', function ($location) {
var vm = this;
vm.redirect = function () {
$location.url('/search');
}
});
})();
Here is my button
<button class="btn default-btn advancedbtn" ng-click="redirect()">Advanced</button>
And here's part of my route file if that will help at all.
.state('index.topnavbar', {
url: '/topnav',
templateUrl: 'app/components/common/topnavbar.html',
controller: 'navbarCtrl as vm'
})
.state('index.search', {
url: '/search',
templateUrl: 'app/components/common/topnav_advancedmodal.html',
controller: 'AdvancedSearchCtrl as vm',
data: {
pageTitle: 'Advanced Search'
}
})
If any other code is needed please let me know. Thanks.
Do you get any errors in the console? Does your template exist? If Angular can't find your template it won't transition to the route. You can check the network requests and console for errors.
You could try using ui-sref:
<a ui-sref="index.search">Advanced</a>
If you prefer to keep the redirect method, can you add a console.log and do you see that log? If not then your scoping is off.
If so, and you prefer to keep your redirect method rather than use ui-sref (in case you want to check something before redirecting), you can inject $state into your controller and call the method:
$state.go('index.search');
Update to add to follow-up question
To help with your follow-up question of reloading if clicking once you're already there, according to the UI-Router documentation, you can specify the option to reload like this:
<a ui-sref="index.search" ui-sref-opts="{ reload: true }">Advanced</a>
Your call for redirect method are not in the scope. You have to change the redirect() to vm.redirect() in the html.
before:
<button class="btn default-btn advancedbtn" ng-click="redirect()">Advanced</button>
after:
<button class="btn default-btn advancedbtn" ng-click="vm.redirect()">Advanced</button>
This might help you
When you alias controller with some name you need to use aliasName in your view
change you code
<button class="btn default-btn advancedbtn" ng-click="vm.redirect()">Advanced</button>
Refer: https://docs.angularjs.org/api/ng/directive/ngController

Controller is not being reset after href call

I have a AngularJs controller in Ionic Framework.
.controller('LocationDetailCtrl', ['$scope','$cordovaGeolocation','$cordovaCamera', '$cordovaFile','$stateParams','Location', LocationDetailCtrl]);
function LocationDetailCtrl ($scope, $cordovaGeolocation, $cordovaCamera, $cordovaFile, $stateParams, Location) {
$scope.locationRow = {};
$scope.test = "";
$scope.images = [];
Location.getById($stateParams.locationId).then(function(result){
//alert("I'm in");
$scope.locationRow = result;
});
}
I have code in view somewhere that does this:
<ion-item class="item-remove-animate item-icon-right" ng-repeat="location in locations" type="item-text-wrap" href="#/locations/{{location.id}}/all">
<h2>{{ location.aplicant_name}}</h2>
<p>{{ location.form_type }}</p>
<i class="icon ion-chevron-right icon-accessory"></i>
<ion-option-button class="button-assertive" ng-click="remove(location)" translate>Delete</ion-option-button>
</ion-item>
In my stateprovider I have this:
.state('location-detail', {
url: '/locations/{locationId}',
abstract: true,
templateUrl: 'templates/location-detail.html',
controller: 'LocationDetailCtrl'
})
.state('location-detail.all', {
url: '/all',
views: {
'loc-detail-view': {
templateUrl: 'templates/location/location-map-all.html'
}
}
})
My problem is, on the first href click I get the values for database, its all alright. But when I go back and press another list time, I would get the same value I got earlier.
Turns out Location.getById() is not being called the second time around.
Never-mind, I found the answer.
Turns out my controller is being cached by default.
I modified the state provider with this code and it now refreshes the view with new model.
.state('location-detail', {
url: '/locations/{locationId}',
cache: false,
abstract: true,
templateUrl: 'templates/location-detail.html',
controller: 'LocationDetailCtrl'
})
The difference here is cache:false.
Cheers!
Ionic views are cached by default, However you can manually set the cache to false in the view, this will make the controller to load again.
read more here, How ever what you have done is also correct, But I personally prefer the method I mentioned here as it will give more control
If you want to keep your page cached for any reason you could wrap all of your function you need to run inside of another funciton and then on the event $ionicView.beforeEnter or afterEnter or enter, you can call that function. Then you can keep the page cached and still have all of your functions run everytime the page is entered. For example in an app i made I did not want to have the homepage uncached, but i need some funcitons to pull
fresh data everytime the page is entered. So I did this:
$scope.$on('$ionicView.beforeEnter', function () {
$scope.doRefresh();
});
That way the page can stay cached but my app still behaves like I want it to. Take a look at some more of the ionicView methods: http://ionicframework.com/docs/api/directive/ionView/

How can I create clickable table rows which route to the same partial in angular?

I am new to AngularJS.
I fetch some items from a server into a table.
Now I want to be able to click on any table row and then route to a specific partial. (let's name it item-info)
I also want my route to change to something like "#/{{item.name}}". I don't want to specify my route name each time because I don't know which row the user clicks on.
Also I don't want to lose which item the user clicked on in the previous page. I need the 'item.name' element.
I'm not sure if I should use ng-click or a simple tag that has href="#/item.name".
<td>{{item.name}} </td>
Thanks,
Try this:
<div ng-controller="ctrl">
<td><a ng-click="onclick($event)" href="#/item-info">{{item.name}}</a> </td>
</div>
Controller:
app.controller('ctrl', function($scope, $location) {
$scope.onclick = function($event) {
$event.preventDefault();
// do extra stuff
var href = angular.element($event.target).attr('href');
$location.path(href);
});
});
Finally could do it by having an ng-href for my click action like this:
ng-href="#/{{item.id}}"
then in my routeProvider:
$routeProvider.when('/:id', {templateUrl: 'item-detail.html', controller: 'ItemDetailController'});
and then in my ItemDetailController I use $routeParams.id to access exactly what will be shown in the url (this takes the ":id" part as shown in the routeProvider)
Now the problem I had with it though was that instead of writing $routeProvider.when('/:id', in the provider I wrote $routeProvider.when('/:item-id', and somehow the dash character messed it up!!
I removed it and now the $routeParams.id is known to my program and I use it.

Conditional partials in Angular.js

Angular novice here. I'm trying to wrap my head around the right way to accomplish a basic template issue.
I have a header, which should read “click here to log in” when the user is not logged in, and “Welcome, Dudefellah” (and associated Settings links and whatnot) when a user is logged in.
I've written a Service that is able to return a JSON bundle including a login state and username, but I don't know what “The Angular Way” to express: “if(auth.loggedin), output partials/header.html; else output partials/header_login.html”.
I’m unclear as to whether this logic would belong in the controller, or some kind of “auth” model, or even in the view (that can't be right, right?). Any assistance would be greatly appreciated.
Within the controller once the login state is fetched create a scope variable headerTemplate and assign the name of the template depending on the login state
function MyCtrl($scope, loginService) {
$scope.auth = loginService.getLoginState();
$scope.headerTemplate = $scope.auth ? 'partials/header.html' : 'partials/header_login.html';
}
In in your markup
<div ng-include src="headerTemplate"></div>
There's a sample angular application called angular-app that does this really well. They have a security service, then a toolbar partial and directive that shows things depending on the state.
https://github.com/angular-app/angular-app/tree/master/client/src/common/security
from angular-app:
src/common/security/login/toolbar.tpl.html:
<ul class="nav pull-right">
<li class="divider-vertical"></li>
<li ng-show="isAuthenticated()">
{{currentUser.firstName}} {{currentUser.lastName}}
</li>
<li ng-show="isAuthenticated()" class="logout">
<form class="navbar-form">
<button class="btn logout" ng-click="logout()">Log out</button>
</form>
</li>
<li ng-hide="isAuthenticated()" class="login">
<form class="navbar-form">
<button class="btn login" ng-click="login()">Log in</button>
</form>
</li>
</ul>
src/common/security/login/toolbar.js:
angular.module('security.login.toolbar', [])
// The loginToolbar directive is a reusable widget that can show login or logout buttons
// and information the current authenticated user
.directive('loginToolbar', ['security', function(security) {
var directive = {
templateUrl: 'security/login/toolbar.tpl.html',
restrict: 'E',
replace: true,
scope: true,
link: function($scope, $element, $attrs, $controller) {
$scope.isAuthenticated = security.isAuthenticated;
$scope.login = security.showLogin;
$scope.logout = security.logout;
$scope.$watch(function() {
return security.currentUser;
}, function(currentUser) {
$scope.currentUser = currentUser;
});
}
};
return directive;
}]);
You could also use ui-router which does wonders for conditional routing and for good infrastructure in general. You'll need to define two states:
myapp.config(function($stateProvider, $urlRouterProvider){
...
// Now set up the states
$stateProvider
.state('login', {
parent: account,
url: "/login",
templateUrl: "partials/header_login.html"
})
.state('auth', {
parent: account,
url: "/authorized",
templateUrl: "partials/header.html"
})
})
when you are back from your query, change state by $state.transitionTo('login') or ('auth') and the router will load the right template for you (and also the URL). in general its much better to use a good router as the basis of your app and not give ad-hoc solutions per each case. you could also read a page (I wrote) about it here

Resources