pre-selected angularjs with ng-repeat - angularjs

This is my HTML
<select ng-model="selectedToggle" ng-change="changedValue()">
<option ng-repeat="x in toggle" value="{{x.data}}" ng-selected="">{{x.name}}</option>
</select>
This is my angularjs
var app = angular.module('myApp', []);
app.controller('namesCtrl', function($scope, $http) {
$scope.toggle = [
{data: "orderer", name: "Orderer"},
{data: "creator", name: "Creator"}
]
$scope.selectedToggle = $scope.toggle[1];
});
Im using the ng-repeat over ng-options is I want to put the data to value
This line $scope.selectedToggle = $scope.toggle[1]; will work only if I use ng-options is their any way to make a pre-selected while the value of <options> will have an orderer and creator

It should be like this
$scope.selectedToggle = $scope.toggle[1].data;

Related

angular select default to first option

I cannot seem to get my dropdown to default to having the first store selected.
html:
<select
id="store"
class="form-control input-inline input-medium"
ng-model="orderVm.Stores.selectedStore.id">
<option
ng-repeat="store in orderVm.Stores"
value="{{store.Id}}">
{{store.MarketplaceName}}
</option>
</select>
{{orderVm.Stores.selectedStore}}
vm.Stores (loaded from a local JSON file):
[
{
"Id": 1,
"MarketplaceId": 1,
"MarketplaceName": "Etsy"
]
},
{
"Id": 2,
"MarketplaceId": 2,
"MarketplaceName": "Shopify"
}
]
controller:
angular
.module('WizmoApp')
.controller('orderController', orderController);
orderController.$inject = ['$http', '$location', 'toastr', 'DTColumnDefBuilder', 'DTOptionsBuilder', 'Cart', 'OrderService', 'PackageService'];
function orderController($http, $location, toastr, DTColumnDefBuilder, DTOptionsBuilder, Cart, OrderService, PackageService) {
var vm = this;
vm.Stores = json; //from file
vm.Stores.selectedStore = {
id: vm.Stores[0].Id,
name: vm.Stores[0].MarketplaceName
};
OrderService.getOrdersGroupedByStore(function (json) {
vm.Stores = json;
vm.selectedStore = {};
});
routes.js:
.state('layout.orders', {
url: '/orders',
templateUrl: '/Content/js/apps/store/views/order.html',
controller: 'orderController',
controllerAs: 'orderVm',
data: { pageTitle: 'Orders' }
})
(It doesn't help that the first option is blank, but first things first.)
I'd use ng-options but frankly, it's even more obscure than this.
https://jsbin.com/kanaco/edit?html,js,output
I write a sample code for you.
Use ng-options for select.
edit:
<select id="store" class="form-control input-inline input-medium"
ng-model="ctrl.selectedStores"
ng-options="item.MarketplaceName for item in ctrl.Stores"
ng-init="ctrl.selectedStores=ctrl.Stores[0]">
</select>
You can use ng-options for repeat option, and use ng-init for default select.
Never use ng-repeat to build select options. Instead, use ng-options, which has a dedicated directive for this:
<select
id="store"
class="form-control input-inline input-medium"
ng-model="orderVm.Stores.selectedStore"
ng-options="store.ID as store.MarketplaceName for store in orderVm.Stores">
</select>
In your controller, you need to assign a default value to the select model:
orderVm.Stores.selectedStore = 1;
This would cause the Etsy option to be selected when the controller loads. Note that the model is just an id here, you don't need to use an object. The reason you were getting an empty option is that Angular could not bind the model to any of the options.
I had a very similar problem to yours and was asissted by a kind guru.

AngularJS - Currency exchange filter with external output

I am trying to build a filter based on this post. I want to be able to switch from one currency to the other by switching a select input with an ng-click on it, but I'm failing to get the input into the filter.
My html is:
<div ng-controller="myCtrl">
you have, {{money | currency}}...<br><br>
</div>
<select>
<option ng-click="currencySymbol = 'USD'; currencyRate=exchange.usd.rate">USD<option>
<option ng-click="currencySymbol = '£'; currencyRate=exchange.pound.rate">£<option>
<option ng-click="currencySymbol = '€'; currencyRate=exchange.euro.rate">€<option>
</select>
And the Angular part:
angular
.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.money = 100;
$scope.exchange = [
{"usd":{"rate":1}},
{"pound":{"rate":0.702846}},
{"euro":{"rate":0.885055}}
];
})
.filter('currency', function() {
var defaultCurrency = 'USD';
return function(input, currencySymbol, currencyRate) {
var out = "";
currencySymbol = currencySymbol || defaultCurrency;
currencyRate = currencyRate || 1.00;
out = input * currencyRate;
return out + ' ' + currencySymbol;
}
});
You can check the JsFiddle here
Thanks in advance!
Quite a few updates here:
First off, your dropdown is located outside of the controller
You could use the ng-options directive to clean up your select menu
You have ng-click on each option which doesn't work well with the complex model you are trying to maintain
If you pass the whole selected option into the filter, you can manage everything from that one scope variable keeping the data in one place
Here is a working example
http://jsfiddle.net/r0m4n/dLLtzqyr/1/
This will be your simplified html:
<div ng-controller="myCtrl">
you have, {{money | currency: selectedCurrency}}...
<br>
<br>
<select ng-model="selectedCurrency" ng-options="item as item.label for item in exchange">
</select>
</div>
And your js:
angular
.module('myApp', [])
// controller here
.controller('myCtrl', function($scope) {
$scope.money = 100;
$scope.exchange = [{
label: "USD",
rate: 1
}, {
label: "£",
rate: 0.702846
}, {
label: "€",
rate: 0.885055
}];
$scope.selectedCurrency = $scope.exchange[0];
})
.filter('currency', function() {
return function(input, selectedCurrency) {
var out = "";
out = input * selectedCurrency.rate;
return out + ' ' + selectedCurrency.label;
}
});
You define 3 parameter in your filter currency. Whenever you use your filter, you need to give these parameters to your filter. In your case :
<div ng-controller="myCtrl">
you have, {{money | currency:currencySymbol:exchange[2].euro.rate}}...<br><br>
</div>
In AngularJS world, you call your filter after the | and you use : as a separator for parameters (the first parameter input is always given implicitly).
To make the debug easier, you can add this in your filter :
return function(input, currencySymbol, currencyRate) {
console.info('currency parameter', input, currencySymbol, currencyRate);
Please note that I hardcoded the parameter currencyRate because it's not handy to retrieve with the way you store your array.

Selected item in ng-options is not displayed in case items are loaded with timeout

I have a stored item value (in local storage), but items collection is loaded from server each time - no need to store it on client side. When the items collection is loaded from server, I want my stored item to be displayed in dropdown list. Here is simplified version of what I have:
controller:
angular.module("myApp", [])
.controller("DemoCtrl", function($scope, $timeout) {
$scope.items = [];
$scope.item = "Two";
$timeout(function() {
$scope.items = ["One", "Two", "Three"];
}, 1000);
});
markup:
<body ng-app="myApp">
<div ng-controller="DemoCtrl">
<select ng-model="item" ng-options="item for item in items">
<option value="">---</option>
</select>
{{ item }}
</div>
</body>
Little demo where you can see, that after 1 second delay, the value is not displayed in dropdown - just a blank space. I've looked at markup and it seems to be ok:
...
<option value="1" selected="selected" label="Two">Two</option>
...
So the value was selected, but just not displaying for some reason.
I've tried to take different versions of Angular and it seems like this behavior is appearing in 1.3.XXX versions: previous (1.2) and next (1.4-beta) versions work fine.
I don't want to downgrade to 1.2, and 1.4 is still in beta, so I've figured out a workaround for this - if I change ng-options a little bit:
ng-options="item for item in items track by item"
It starts working as it should. But I still would like to know, what is the reason of this weird behavior.
Wait to set the selected item until the array is populated like this:
angular.module("myApp", [])
.controller("DemoCtrl", function($scope, $timeout) {
$scope.items = [];
$timeout(function() {
$scope.items = ["One", "Two", "Three"];
$scope.item = "Two";
}, 1000);
});

How to set the value property of a select when using angular

I can successfuly bind an array to a select tag in angular using this syntax:-
var mainApp = angular.module('mainApp', []);
mainApp.controller('mainController', [
'$scope',
function ($scope) {
$scope.testArray = [{ text: '1st', value: 1 }, { text: '2nd', value: 2 }];
}]);
My HTML is like this:-
<select ng-model="testModel" ng-options="theTitle.text as theTitle.text for theTitle in testArray"></select>
However this creates an option list like this:-
<select ng-options="theTitle.text as theTitle.text for theTitle in testArray" ng-model="testModel" class="ng-pristine ng-valid">
<option value="?"></option>
<option value="0">1st</option>
<option value="1">2nd</option>
</select>
How do you bind the value property in the array to the option value attribute and why does it display the first option as a ?
Is there something else I need to put in my ng-options attribute?
in in html section:
<select ng-model="testModel" ng-options="theTitle.text for theTitle in testArray"></select>
in javascript section
var mainApp = angular.module('mainApp', []);
mainApp.controller('mainController', [
'$scope',
function ($scope) {
$scope.testArray = [{ text: '1st', value: 1 }, { text: '2nd', value: 2 }];
$scope.testModel = $scope.testArray[0];
}]);
The reason that ? Is showing is because your ngModel has not been initialized. In mainController, initialize testModel to '1st'. You will see that the ? goes away, and your drop down list is initialized to your first item
In ng-options, the format goes value as alias, so you need:
<select ng-model="testModel" ng-options="theTitle.value as theTitle.text for theTitle in testArray"></select>
The ? option is created because your model value does not exist as an option in the select, so the browser adds it to display the input as empty. To fix it you want to initialise the model to a valid value, something like: ng-init="testModel = testArray[0].value"

Not able to load $http.get - JSON data in ui tabset child tabs

I tried to load a dropdown with the response got from http post. But its failing to load on child tabs.
When i click next button from tab1. I make a post call and get a JSON back. Using the returned data i want to load a dropdown in my second tab.
I already raised a query on tabset and it worked fine. Now I modified the plunker little bit. I did the same way mentioned in the below link. But i'm missing something when i try to do the samething with $http.get
Tabset $rootScope scope not updating
app.js
angular.module('plunker', ['ui.bootstrap'])
.service('Common', function() {
this.tabData = {};
})
.controller('SampleController', function($scope, $http, Common) {
$scope.submitTab1 = function() {
$http.get("post.json", {
// Some logic
}).success(function(data) {
Common.tabData = data;
$scope.steps.step2 = true;
});
}
})
.controller("SampleTab2Controller", function($scope, Common) {
$scope.userList = Common.tabData;
});
Html
<tabset ng-init="steps={step1:true, step2:false}">
<tab heading="Step 1" active="steps.step1">
<div data-ng-controller="SampleController">
<form data-ng-submit="submitTab1()">
<label>Some Operations ...</label>
<br>
<br>
<label>Click next to retrieve json from server ...</label>
<button type="submit">Click Next</button>
</form>
</div>
</tab>
<tab heading="Step 2" active="steps.step2">
<div data-ng-controller="SampleTab2Controller">
<form name="step2">
<p>load the json list from Tab1 controller </p>
<select ng-model="selectedUser" ng-options="user.title for user in userList">
<option value="">--- select ---</option>
</select>
</form>
</div>
</tab>
</tabset>
Post.json
[
{
"id": 1,
"title": "Arnold"
},
{
"id": 2,
"title": "stallone"
}
]
Plunker Code http://plnkr.co/edit/EZC1d6tDDZlpWZUHY6os?p=preview
Your issue has nothing to do with loading from http, but it has to do with properly copying reference of objects.
When you do $scope.userList = Common.tabData; the reference of tabData is copied to userList, and then when the tabData is updated using Common.tabData = data now tabData in the service points to a different reference and $scope.userList keeps pointing to the old one. So instead of getting the reference of tabData and copying it to the userList, set up the service object itself on the scope.
In your controller change $scope.userList = Common.tabData to $scope.userList = Common :-
.controller("SampleTab2Controller", function($scope, Common) {
$scope.userList = Common;
});
and in the view iterate upon userList.tabData
<select ng-model="selectedUser" ng-options="user.title for user in userList.tabData">
Plnkr
If I modified your code this way it works
1) changed tabData to be an array
2) Used angular.copy instead of asignning
.service('Common', function() {
this.tabData = []; ==> Changed this to array
})
$http.get("post.json", {
// Some logic
}).success(function(data) {
angular.copy(data,Common.tabData); ==> Used angular copy so it copies the array
$scope.steps.step2 = true;
});
Updated Plnkr
main issue in your code is controller get executed first and then Common.tabData is loaded.so can do like this:
angular.module('plunker', ['ui.bootstrap'])
.service('Common', function() {
this.tabData = {};
})
.controller('SampleController', function($scope,$http, Common) {
$scope.submitTab1 = function() {
$http.get("post.json", {
// Some logic
}).success(function(data) {
Common.tabData = data;
$scope.steps.step2 = true;
});
}
})
.controller("SampleTab2Controller", function($scope, Common) {
$scope.userList = Common;
});
and html code according to this is:
<div data-ng-controller="SampleTab2Controller">
<form name="step2">
<p>load the json list from Tab1 controller </p>
<select ng-model="selectedUser" ng-options="user.title for user in userList.tabData">
<option value="">--- select ---</option>
</select>
</form>
</div>

Resources