move to different pages based on the checked radio button - javascript

i have this form and it has 3 ionic radio buttons used.Is there a way to a move to different pages according to the radio buttons that are selected.For ex: my radio buttons are named
1.USO
2.OASO
3.TFTSO
I want to move to a different page if i select USO , and to another different page if i choose OASO and so on. I want to move only after i click the 'Proceed' Button that i've implemented in my code.
This is how i've implemented by radio buttons and proceed button in html
<label class="labelColor">
<h5><b>Select Standing Order Type</b></h5>
</label>
<div class="list">
<ion-radio ng-repeat="item in clientSideList"
ng-value="item.value"
ng-model="data.clientSide">
{{ item.text }}
</ion-radio>
</div>
<!-- BUTTONS -->
<div class="col"
style="text-align: center">
<button align="left"
class="button button-block button-reset"
style="display:
inline-block;width:100px;text-align:center "
type="reset"
ng-click="submitted = false; reset()"
padding-top="true">
Reset
</button>
<button class="button button-block button-positive"
style="display: inline-block;width:100px "
ng-click="submitted=true; "padding-top="true">
Proceed
</button>
</div>
my angularjs
.controller('OrderCtrl', function($scope,$state) {
$scope.clientSideList = [
{ text: "Utility Standing Order", value: "uso" },
{ text: "Own Account Standing Order", value: "oaso" },
{ text: "Third Party Fund Transfer Standing Order", value: "tpftso" }
];
$scope.data = {
clientSide: 'uso'
};
})
My controller
.controller('OrderCtrl', function($scope,$state, $http, $ionicPopup) {
$scope.clientSideList = [
{ text: "Utility Standing Order", value: "uso" },
{ text: "Own Account Standing Order", value: "oaso" },
{ text: "Third Party Fund Transfer Standing Order", value: "tpftso" }
];
$scope.data = {
clientSide: 'uso'
};
$scope.move = function () {
var path;
switch($scope.data.clientSide) {
case 'uso': path = '/so/utilitystanding'; break;
case 'oaso': path = '/so/ownstandingorder'; break;
case 'tpftso': path = '/so/thirdstandingorder'; break;
}
$state.go(app.standing);
};
})
.controller('utilityStandingCtrl', function($scope,$state) {
});

Try to add ng-click to your Proceed button and define function which will analyse value of your selected data.clientSide and then call $location.path(url). You need to inject $location service into your controller.
JavaScript:
$scope.goSomewhere = function () {
var path;
switch($scope.data.clientSide) {
case 'uso': path = '/uso'; break;
case 'oaso': path = '/oaso'; break;
case 'tpftso': path = '/tpftso'; break;
}
$location.path(path);
};
And HTML:
<button ng-click="goSomewhere()">Proceed</button>
Demo: http://plnkr.co/edit/jawx0OivVmu2EyNmAbR9?p=preview
Edit
My answer above is related to angular-route, not to ui-router. In the last you need to use all the same code except of function call. Instead of location.path() it must me
$state.go(yourStateName)
Please note, not url, but state name.
Edit2
Here is code for ionic framework (almost the same) + settings of application.
Config:
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('main', {
url: "/main",
templateUrl: 'main.html'
})
.state('usoStateName', {
url: '/uso',
templateUrl: 'page.html',
controller: 'usoCtrl'
})
.state('oasoStateName', {
url: '/oaso',
templateUrl: 'page.html',
controller: 'oasoCtrl'
})
.state('tpftsoStateName', {
url: '/tpftso',
templateUrl: 'page.html',
controller: 'tpftsoCtrl'
});
$urlRouterProvider.otherwise('/main');
});
And function:
$scope.goSomewhere = function () {
var path;
switch($scope.data.clientSide) {
case 'uso': path = 'usoStateName'; break;
case 'oaso': path = 'oasoStateName'; break;
case 'tpftso': path = 'tpftsoStateName'; break;
}
$state.go(path);
};
Demo: http://plnkr.co/edit/0sk3dECPNm35HgMqiprt?p=preview

Instead of {{ item.text }}
Try something like this:
a href=""#/viewName/{{item.text }}"}">{{ item.text }}

Related

$state.go doesn't pass parameters

This is the part of my HTML:
<td>
<button class="btn btn-primary" ui-sref="edit({id: v.customerId})" ui-sref-opts="{reload: true}">Edit</button>
<button class="btn btn-primary" ng-click="removeRow(v.firstName);">Delete</button>
</td>
as you can see I am passing the customerId as and id to be one of the parameters displayed in the url
app.js:
var app = angular.module('webtrekkApp', ['ngSanitize', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('edit', {
name: 'edit',
url: '/users/:id/edit',
templateUrl: './views/customer-details.html',
controller: 'ctrl',
params: {
obj: null
}
});
});
ctrl.js:
//If 'initData' isn't set, then set it up by default
if(!localStorage.getItem('initData')) {
$window.localStorage.setItem('initData', JSON.stringify($scope.initData));
}
$scope.retrievedData = JSON.parse($window.localStorage.getItem('initData'));
for (var i = 0; i < $scope.retrievedData.length; i++) {
$scope.retrievedData[i].birthdayDate = new Date().getFullYear() - new Date($scope.retrievedData[i].birthdayDate).getFullYear();
}
$scope.sortedType = 'firstName';
$scope.sortedReverse = false;
//Remove Rows and Update localStorage Key Values
$scope.removeRow = function(name) {
var index = $scope.retrievedData.findIndex(function(obj) {return obj.firstName === name});
$scope.retrievedData.splice(index, 1);
window.localStorage.setItem('initData', JSON.stringify($scope.retrievedData));
};
$state.go('edit', {obj: $scope.retrievedData});
So I a table, and when users clicks on 'edit', I need THAT object to be passed to the ui.router so I can display it in customer-details.html. How can I do it? I am doing something wrong here. I have read all the documentation on ui.router but do not know should $state.go be defined in the initial controller or in some other. Also I've followed this question, but couldn't get it to work: How to pass custom data in $state.go() in angular-ui-router?
In your edit state you have two parameters, id and obj, one of which inside the url.
But when you trigger the state from your controller you are not passing the id parameter and you did not define a default value
$state.go('edit', {obj: $scope.retrievedData});
try adding it inside your params object
params: {
obj: null,
id: null
}
EDIT:
to answer your further question:
<button class="btn btn-primary" ng-click="handleItem(v);">Go to Edit state</button>
$scope.handleItem = function(item){
//here extract your item specific data from $scope.retrievedData then change the state
var itemData = getItemData(item, $scope.retrieveData);
$state.go('edit', {obj: itemData});
}
Hi you are not using controller, if you want to pass parameters to $state.go() you should have controller to get that value in particular state.
app.js
var app = angular.module('webtrekkApp', ['ngSanitize', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('edit', {
name: 'edit',
url: '/users/:id/edit',
templateUrl: './views/customer-details.html',
controller: 'myController',
params: {
obj: null
}
});
});
in Controller
function myController($state) {
conrole.log($state.params.obj);
}

Pass parameters by clicking button to other controller

i got to do a simple CityBike Application for a class at university.
To complete the task, i give the user the possibility to choose between three cities and showing all the free bikes and empty city bike spots at the moment, going forward. Through the service.js I include the api for the citybikes.
I now got two views (start.html & citybikes.html) and i would like to choose one of the three cities in the Dropdown menu and pass it to citybikes.html-controller by clicking on the button.
Is there any simple way to accomplish that?
Here's the main part of the code for the start.html:
<label class="item item-input item-select">
<div class="input-label">
Stadt auswählen
</div>
<select ng-model="choose.name">
<option ng-repeat= "city in citystart"> {{city.CityName}}</option>
</select>
</label>
<p> anzeige? {{choose.name}}</p>
<!--BUTTON-->
<a ng-if="choose.name"
class="button button-block button-positive"
ui-sref="tab.citybike({param1: choose.name})">
CityBikes anzeigen
</a>
And here are the controller:
angular.module('starter.controllers', [])
.controller('Start', function($scope, $stateParams, cities_overview) {
//$scope.citystart = cities_overview.getCities();
})
.controller('CityBikeController', function($scope, $stateParams, CityBikeParis, CityBikeHamburg, CityBikeLondon, cities_overview, chosencities) {
$scope.chosenVar = "";
$scope.chosenVar = $stateParams.param1;
$scope.SumFree=0;
$scope.SumEmpty=0;
var liste = CityBikeHamburg.getList();
switch($scope.chosenVar){
case "Paris":
liste = CityBikeParis.getList();
break;
case "Hamburg":
liste = CityBikeHamburg.getList();
break;
case "London":
liste = CityBikeLondon.getList();
break;
}
liste.then(function(list) {
$scope.stationlist = list.data.network.stations;
for(var i=0; i<$scope.stationlist.length; i++){
$scope.SumFree += $scope.stationlist[i].free_bikes;
$scope.SumEmpty += $scope.stationlist[i].empty_slots;
}
})
})
Finally an excerpt of my app.js that routes the views:
.state('tab.citybike', {
url: '/citybike',
parameter: {
'param1':""
},
views: {
'tab-citybike': {
templateUrl: 'templates/citybike.html',
controller: 'CityBikeController'
}
}
});
I would be very very grateful if anyone could help me out! :)
Greets,
Thomas
You can pass parameter in state param.
Routing :
$stateProvider
.state('tab.citybike', {
url: '/citybike/:param1',
views: {
'tab-citybike': {
templateUrl: 'templates/citybike.html',
controller: 'CityBikeController'
}
},
...
}
Controller :
var param = $stateParams.param1; //get param1 value.
Html :
ui-sref="tab.citybike({param1: choose.name})"

AngularJS: Update JSON in modal with specific key

What's the best practice to update json in view with specific key.
In my case, i want to update feedback from 'not answered' to 'answered' .
[
{
"id": "34",
"mac_address": "cd:9e:17:64:1b:42",
"question": "Help me",
"time": "2016-03-16 16:22:08",
"is_answered": false
}
]
to
[
{
"id": "34",
"mac_address": "cd:9e:17:64:1b:42",
"question": "Help me",
"time": "2016-03-16 16:25:29",
"is_answered": true
}
]
There is some list my customer feedbacks:
<div class="parent" ng-repeat="customer in customers">
<h2>{{customer.id}}</h2>
<p>{{customer.question}}</p>
<h4 ng-show="{{customer.is_answered}}">Answered</h4>
<h4 ng-show="!{{customer.is_answered}}">Not Answered</h4>
<button ng-show="!{{customer.is_answered}}" ng-click="showModal()">Reply</button>
</div>
When i click reply button,then appear modal with some inputs to response my customer complaints.
<div id="modal">
<textarea placeholder=""response></textarea>
<button ng-click="submit()">Reply</button>
</div>
i want to update based of feedback id, and again, what the best practice how to do it?
You can pass the customer object with showModal call.
<div class="parent" ng-repeat="customer in customers">
<h2>{{customer.id}}</h2>
...
<button ng-show="!{{customer.is_answered}}" ng-click="showModal(customer)">Reply</button>
</div>
Inside your controller, save this passed in customer. Once modal closed, update is_answered property of that customer.
$scope.showModal = function (customer) {
var selected_customer = customer;
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
customer: customer
});
modalInstance.result.then(function () {
selected_customer.is_answered = true;
}
};
Found my solution, based on Pass input value to $mdDialog.
vm.showModal = function(e, message) {
$mdDialog.show({
clickOutsideToClose:true,
// locals:{ name: 'Bob'},
controller: function ($mdDialog) {
var vm = this;
vm.message = {};
vm.message = message;
$scope.hide = function () {
$mdDialog.hide();
};
$scope.cancel = function () {
$mdDialog.cancel();
};
},
controllerAs: 'modal',
templateUrl: 'feedbackForm.html',
parent: angular.element(document.body),
targetEvent: e,
});
};
In my view :
<h5 style="">{{modal.message.id}}</h5>
Thank you guys

AngularJS Custom Filter getting invoked multiple times with one change

Following are my questions on the code described below -
On page load, my below custom sort filter is getting called multiple times. why?
On selecting a select option (from directive), I want to trigger filter based on selected value (using two way binding). Here again filter is being called thrice. Why?
Can some one point me to answers? I know that Angular does a Dirty Check by comparing old and new digest, but why multiple and 3rd invocation (as mentioned in the above questions).
I have below directive -
angular.module("customDirectives", [])
.directive("sortAll", function () {
return {
restrict: "E",
scope: {
columns: "=sortcolumns",
optionselected: "=selectedoption"
},
templateUrl: '../Views/Directives/SortAll.html',
controller: function ($scope) {
$scope.sortOptions = [];
var asc = 'Ascending';
var desc = 'Descending';
$scope.getSortOptions = function () {
angular.forEach($scope.columns, function (item) {
$scope.sortOptions.push({ name: item + '-' + asc, value: asc });
$scope.sortOptions.push({ name: item + '-' + desc, value: desc });
});
$scope.optionselected = $scope.sortOptions[1];
return $scope.sortOptions;
}
}
};
});
Directive HTML -
<select name="sortOptions" id="sortOptions" class="form-control width-20percent pull-right"
ng-options="option.name for option in sortOptions"
ng-init="getSortOptions()"
ng-model="optionselected"></select>
And below Filter -
angular.module("customFilters", [])
.filter("sort", function ($filter) {
return function (data, sortOption) {
console.log(sortOption);
if (angular.isArray(data) && angular.isObject(sortOption)) {
var options = sortOption["name"].split('-');
var xc = options[1] == 'Ascending' ? false : true;
return $filter("orderBy")(data, options[0], xc);
} else {
return [];
}
}
});
Now my Controller code -
angular.module("productStore")
.controller("ProductListCtrl", function ($scope, $filter) {
});
And the main controller which gives the data -
angular.module("productStore")
.constant("dataUrl", "http://localhost:57398/testdata/Products.json")
.constant("productColumns", ["name","price","description"])
.controller("MainCtrl", function ($scope, $http, dataUrl, productColumns) {
$scope.data = {};
$scope.productColumns = productColumns;
$http.get(dataUrl)
.success(function (products) {
$scope.data.products = products;
})
.error(function (error) {
$scope.data.error = error;
})
});
HTML -
<body ng-controller="MainCtrl">
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">PRODUCT STORE</a>
</div>
<div class="panel-default" ng-controller="ProductListCtrl" ng-hide="data.error" ng-cloak>
<div class="col-xs-8">
<sort-All sortcolumns="productColumns" selectedoption="selectedSortOption"></sort-All>
<div class="well padding-top-0px" ng-repeat="product in data.products | sort:selectedSortOption">
<h3>
<strong>{{product.name}}</strong>
<span class="pull-right label label-primary">
{{product.price | currency}}
</span>
</h3>
<span class="lead">{{product.description}}</span>
</div>
</div>
</div>
</body>
Sample Data -
[{
"category": "Watersports",
"description": "A boat for one person",
"name": "Kayak",
"price": 275,
"id": "05af70919155f8fc"
}]
On Page load -
On changing item in select -

Angular Directive Element dynamic Template fields with its updated model value from controller?

I have <superhero> directive which has two directive
web-buttons to take of the form validation and post the updated
ngModel value to respective controller
fieldMap directive to generate the dynamic fields by object we are passing from respective controller
Here is the example which i have worked
directive attribute called saveFormFn will tell the button to call which function to invoked using enter attribute directive.
For example. After click save button it will call the function 'Ctrl1saveFormFn' from controller Ctrl1 .This function will make ajax post to save the form fields.
After updating the text fields with some content and click save,I have passed the current scope of the directive to respective controller (see console log). i could not get the updated fielddata value from current Scope.
$scope.Ctrl1saveFormFn = function(item){
_.each(item,function(currentScope){
console.log(currentScope)
// here i want to collect the form data with updated fielddata values
})
}
I am beginner.Am i on right path? Please advice
I've re-written your code because it was pretty hard to understand.
I would do it like this:
Use ng-include to load the template of your buttons. That's loading the control buttons edit and save.
Save your data in a variable in the superhero directive. Maybe it would be even better to store it in a separate service/factory.
Create a directive customForm that will create a form based on the supplied model that you're passing to its scope.
The main application logic is in the superhero directive because it is adding the controls save/edit to the DOM. If saving/editing is not only related to the superhero it would be better to do it in your main controller.
Please have a look at the demo below or in this jsfiddle.
angular.module('demoApp', [])
.directive('superhero', Superhero)
.directive('customForm', CustomForm)
.controller('mainController', MainController);
function Superhero() {
return {
restrict: 'E',
scope: {
formModel: "=",
},
template: '<div class="hero"><div ng-include="\'web-buttons.html\'"></div><custom-form model="formModel"></custom-form></div>',
controllerAs: 'superHeroCtrl',
controller: function ($scope) {
var self = this;
console.log('controller directive');
angular.extend(this, {
abilities: [],
editMode: false,
addStrength: function (data) {
self.abilities.push(data);
},
getStrength: function () {
return self.abilities;
},
showSave: function() {
self.editMode = true;
$scope.formModel.editMode = true;
},
hideSave: function() {
self.editMode = false;
$scope.formModel.editMode = false;
},
save: function() {
self.addStrength('can fly');
console.log(self.getStrength());
console.log('saving data now of form now...', $scope.formModel.data);
alert('saving data of form now: ' + self.getStrength()[0] + ' - ' + JSON.stringify( $scope.formModel.data, null, 2));
self.hideSave();
}
});
}
}
}
function CustomForm() {
return {
restrict: 'EA',
scope: {
model: '='
},
template: '<div ng-if="model.editMode" ng-repeat="formElement in model.fields" ng-include="formElement.template.url"></div>'
}
}
function MainController() {
this.normalForm = {
editMode: false,
data: {
},
fields: {
'NAME':{
template: {
url: 'customForms/text.html',
type: 'edit' // not sure for what it is needed
},
label: 'First name',
id: "NAME",
placeholder : "First Name",
fieldData: "NAME",
key : 'first_name'
},
'LNAME': {
template: {
url: 'customForms/text.html',
type: 'edit' // not sure for what it is needed
},
label: "Last Name",
placeholder : "Last Name",
id: "LNAME",
key : 'last_name'
}
}
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as mainCtrl">
<script type="text/ng-template" id="customForms/text.html">
<label for="{{formElement.id}}">{{formElement.label}}</label>
<input ng-model="model.data[formElement.key]" placeholder="{{formElement.placeholder}}" id="formElement.id"/>
</script>
<script type="text/ng-template" id="web-buttons.html">
<button ng-click="superHeroCtrl.showSave()" ng-if="!superHeroCtrl.editMode">edit</button>
<button ng-if="superHeroCtrl.editMode" ng-click="superHeroCtrl.save()">save</button>
</script>
<superhero form-model="mainCtrl.normalForm"></superhero>
<h3>debug output:</h3>
<pre>
{{mainCtrl.normalForm |json}}
</pre>
</div>

Categories