how to keep selected option from user when views are changed - angularjs

Demo:
I have a dropdown, and options are being fecthed from JSON.
say
<select ng-model="projectModel" ng-options="project as project.projectName">
<option>one</option>
<option>two</option>
<option>three</option>
<option>four</option>
<option>and so on... </option>
</select>
i have two views page1.html and page2.html
in page1.html i have the following code.
select box with above options when ever user select an option say, user has selected three. this has to be saved somewhere. i dont where to save, so next when user clicks page2.html the data selected before in page1.html should not reset.
HTML :
<body ng-app="staticSelect">
<div ng-controller="ddController">
<form name="myForm">
<label for="singleSelect"> Single select: </label><br>
<select name="singleSelect" ng-model="data.singleSelect">
<option ng-repeat="x in options">{{x}}</option>
</select><br>
<tt>singleSelect = {{data.singleSelect}}</tt>
</form>
</div>
</body>
JS
app.controller('ddController', ['$scope', function($scope) {
$scope.data = {
singleSelect: null,
};
$scope.options = ["red","blue","yellow"];
}]);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '01.html',
controller: 'htmlCtrl',
})
.when('/html', {
templateUrl: '02.html',
controller: 'htmlCtrl',
})
})
any help would be much appreciated!
Thanks

Added a reference for 'ng-cookies' in the main view and a service to set and get a cookie.
In Html:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-cookies.js"></script>
The binding html has the method to set the cookie through ng-change
<select name="singleSelect" ng-model="data.singleSelect" ng-change="setSelect()">
<option ng-repeat="x in options">{{x}}</option>
</select>
You can see the CookieService in the Working Demo
In Controller:
When the setSelect() method is fired the selected value is set in cookie, when the view is returned back to it will re store the value from the cookie
if(cookieService.getAppData("selected") !== null && cookieService.getAppData("selected") !== undefined){
$scope.data.singleSelect = cookieService.getAppData("selected");
}
$scope.setSelect = function (){
cookieService.setAppData("selected", $scope.data.singleSelect);
}

Related

How to select Default option (india) in Angular js?

country names displaying using select box, select option coming from external json file. Based on selected country i am loading state json file into another select box,till every thing is ok, Now I need set Default selected country as INDIA, I tried bellow code.
html
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<select id="country" ng-init="state1 = options['IN']" style="width:250px;" class="" name="selectFranchise" ng-model="state1" ng-change="displayState(state1)">
<option ng-repeat="(key,country) in countries" value="{{key}}">{{country[0]}}</option>
</select>
</div>{{countries}}{{state1}}
<div>
<select id="state" ng-model="cities">
<option ng-repeat="(state,city) in states[state1]" value="{{city}}">{{city}}</option>
</select>
</div>
</div>
script
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.states = {
"IN":[
"Delhi",
"Goa",
"Gujarat",
"Himachal Pradesh",
]
};
$scope.countries = {
IN: ["India"],
ZA: ["South Africa"],
AT: ["Austria"]
}
$scope.lastName = "Doe";
});
jsfiddle
Add this in the controller after defining your $scope.countries
$scope.state1 = Object.keys($scope.countries)[0];
Remove ng-init from Html page.

$watch not displaying change with two ui-views

I have $watch function where it watches whenever a country is selected, but it's not saving the changed data to the scope. I had one ui-view, which worked fine, but then I changed the structure and now have two ui-views under same page, both uses the same controller. Reason for the change was for was to have a clean html page, I could always go back to one ui-view, but it's messy. This is where it started having problems.
here is app.js
$stateProvider
.state('homepage',{
templateUrl: '/static/partial/home/homeLayout.html',
controller: 'UploadFileCtrl',
})
.state('homepage.show',{
url: '/',
views: {
querySetup: {
templateUrl: '/static/partial/home/querySetup.html',
},
queryResults: {
templateUrl: '/static/partial/home/queryResults.html',
},
}
})
layout.html - ui-views:
<div class="col-sm-12 panel-container">
<div class="col-sm-6" style="height: 100%;">
<div ui-view="querySetup" ></div>
</div>
<div class="col-sm-6" style="height: 100%;">
<div ui-view="queryResults"></div>
</div>
</div>
controller watch:
$scope.currentCountries = [
{
name: 'United States',
code: 'US'
},
{
name: 'United Kingdom',
code: 'GB'
},
{
name: 'Germany',
code: 'DE'
},
{
name: 'France',
code: 'FR'
},
{
name: 'China',
code: 'CN'
},
{
name: 'Japan',
code: 'JP'
}
];
$scope.$watch('pickedCountry', function(){
if($scope.pickedCountry != null){
$scope.countryCode = $scope.pickedCountry.code;
}
});
here is querySetup view:
<select name="brand" ng-model = "pickedCountry"
data-ng-options="country as country.name for country in currentCountries">
<option value="">Select Brand</option>
</select>
I moved the controller out of the state homepage, and set for each view under the state homepage.show. This worked fine, but an extra operation is not working. When selecting a brand, it's supposed to run a calculation and set it in the queryResults view. The results is set to a scope which have to be displayed to queryResults.
here is queryResults:
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title">OSM RESULTS</h3>
</div>
<div class="panel-body">
<textarea rows="50" cols="100" class="xmlOutput">
{{ queryResults }}
</textarea>
</div>
</div>
Please help! Not familiar with Angular $watch, and I think the problem comes when there is two ui-views. Thanks in advance for your help.
UPDATE
Found the solution to my problem, so I need to add $parent to my model and pass the changed data as a param to my $watch function:
html update:
<select name="brand" ng-model = "$parent.pickedCountry"
data-ng-options="country as country.name for country in currentCountries">
<option value="">Select Brand</option>
</select>
controller update
$scope.$watch('pickedCountry', function(data){
if(data != null){
$scope.countryCode = data.code;
}
});
This solved the issue, but still don't quite understand why I needed to add the parent. Can someone explain why?
You have your controller set up to live in homepage, but your templates live in homepage.show which is a child state of homepage. In order to access the variables from that controller you can use $parent (as you've discovered) to access the parent state's scope.
I would recommend restructuring your state definition though so you don't have to deal with that.
.state( 'homepage', {
url: '/homepage',
views: {
'':{
templateUrl:'/static/partial/home/homeLayout.html',
controller: 'UploadFileCtrl',
},
'querySetup#homepage': {
templateUrl:'/static/partial/home/querySetup.html'
},
'queryResults#homepage':{
templateUrl:'/static/partial/home/queryResults.html'
}
}
})
I believe it is because child states operate the same as prototypical inheritance (scope: true) on directives.
You might consider defining in your controller:
$scope.input = {};
$scope.$watch('input.pickedCountry', function(data){
if(data != null){
$scope.countryCode = data.code;
}
});
and in the querySetup template:
<select name="brand" ng-model = "input.pickedCountry"
data-ng-options="country as country.name for country in currentCountries">
<option value="">Select Brand</option>
</select>

Select default value in a dropdown using AngularJS with EJS

I mixed EJS and AngularJS in a webapp, but now I'm having problems to load a default value for a dropdown (select element).
I use the same HTML file to add and update users.
I have a URL that return all values loaded in the dropdown, accessed in the Angular controller when the page loads.
This is the controller:
angular.module('app').controller('userCtrl', function($scope, $http) {
...
function getCities() {
$http.get('/rest/cities').then(function(response) {
vm.cities = response.data.records;
});
}
The EJS sends the default value via response (as in this example):
router.get('/user', function(req, res) {
res.render('pages/user', { defatultCity: 10 });
}
The HTML builds the dropdown with this code:
<select id="city" name="city" class="form-control input-sm" required>
<option></option>
<option ng-repeat="x in cities" value="{{x.idCidade}}"> {{ x.Nome }} </option>
</select>
What I have 'unsuccessfully' tried so far (in the HTML):
To validate value from Angular with value from EJS
<option ng-repeat="x in cities" value="{{x.idCity}}" <%if (defaultCity == %> {{x.idCity}} <%) {%> selected <%}%> > {{ x.Nome }} </option>
To insert a hidden input to hold the value in the HTML and inside the controller I added a JQuery
<input type="hidden" id="defaultCity" value"<%=defaultCity%>" />
// In the controller (it return an error - this.each is not a function)
$('city').val($('#defaultCity'))
I know these attempts are ugly, but I could not find a way to make it work yet. I'll be happy if someone knows how to do it.
PS: I would like to avoid passing all the city list of values from NodeJS to use EJS forEach command inside the HTML.
Thank you!
Add this piece of code at the end of your .ejs template
<script type="text/javascript">
angular.module('app')
.value('myCity', <%- JSON.stringify(defaultCity) %>);
</script>
then inject the component in your controller:
app.controller('myCtrl', function ($scope, myCity) {
function getCities() {
$http.get('/rest/cities').then(function(response) {
vm.cities = response.data.records;
// myCity must be an object - same as vm.cities[0], for example
$scope.defaultCity = myCity;
});
});
and change your HTML file to have the default value
<select ng-model="defaultCity"
ng-options="city as city.name for city in cities track by city.id"
id="city" name="city" class="form-control input-sm" required >
<option></option>
</select>

ng-change doesn't work when select value changes

Can you help me please? I have no idea of what this can be.
I'm using a template on my pages and each page has yours file js with angularJS code:
~/Content/Scripts/layout/index.js
~/Content/Scripts/home/home.js
~/Content/Scripts/projetos/projetos.js
I'm trying to call a function when the dropdown value changes, so i using ng-change in a partial-view.
My page _Layout:
<html lang="en" class="no-js" ng-app="App">
...
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<div class="page-content">
#RenderBody()
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</div>
</div>
<!-- END CONTENT -->
My partial-view is loaded when event click on menu occurrs
<div ng-cloak ng-controller="ProjetosController" ng-init="init()">
...
<div class="col-md-3">
<label>Projetos</label>
<div class="input-icon input-icon-lg">
<select ng-change="changed()" data-placeholder="selecione..." class="form-control input-lg select2me" ng-model="Projetos"
ng-options="proj.Nome for proj in Projetos">
<option value=""></option>
</select>
</div>
But nothing happens and any error occurred when I look in Chrome's developer tools.
My controller c#
public JsonResult LoadProjetos()
{
var results = rep.LoadProjetos();//List<Projetos>();
return Json(new
{
projetos = results
}, JsonRequestBehavior.AllowGet);
}
My controller js
var app = angular.module('App');
app.controller('ProjetosController', function ($scope, $http) {
$scope.init = function () {
$("#menu").find('li#projetos').addClass("start active");
$http({
method: 'GET',
url: 'Projetos/LoadProjetos'
}).then(function successCallback(response) {
var projetos = response.data.projetos;
$scope.Projetos = projetos;
}, function errorCallback(response) {
alert(response);
});
}
$scope.changed = function () {
alert('text');
}
});
Any ideas? Thanks all
Try these changes so that your select uses a $scope variable:
<select ng-change="changed()" data-placeholder="selecione..." class="form-control input-lg select2me" ng-model="selectedItem"
ng-options="proj.Nome for proj in Projetos">
<option value=""></option>
</select>
$scope.changed = function () {
alert($scope.selectedItem);
}
http://plnkr.co/edit/uUf9ehxQpBSzVgQasTtN?p=info
If you use AngularJS version 1.2.x and the newest Chrome see this:
https://code.google.com/p/chromium/issues/detail?id=565132
updated to 1.4.5 This should work.
After a long time, i found a solution. The problem is because my ng-model has the same name of the ng-option. I changed it and works fine!
Thx all.

How hide a drop-down list when the model is empty in angularjs?

I need to hide a drop-down list when the model is empty and to show it when there are values in the model.
I have a service to get the values.
angular.module('myApp.services', ['ngResource'])
.factory('OptionsSelect', ['$resource',
function ($resource) {
return $resource('http://myapi/miapp/optionselect/1', {}, {
query: {
method: 'GET',
params: { id: '1' },
isArray: false
}
});
}
])
The possible result is:
{"1":"red","5":"blue","34":"blue"}
or
<pre>
{}
</pre>
In the controller:
$scope.optionsSelect = OptionsSelect.query();
The view is:
<div class="form-group" ng-hide="isHide()">
<select class="form-control" ng-options="key as value for (key, value) in optionsSelect">
</div>
You can view the code in jsfiddle: http://jsfiddle.net/finsi/LMJXC/38/
Hi I've created jsbin for you please have a look. You should add model to you select directive and use $promise like it is below. I hope that will help.
HTML:
<div class="form-group" ng-show="optionsSelect">
<select class="form-control"
ng-model="option.color"
ng-options="key as value for (key, value) in optionsSelect">
</div>
JS:
app.controller('firstCtrl', function($scope, OptionsSelect){
$scope.optionsSelect = {};
OptionsSelect.query().$promise.then(function(optionSelectCollection){
angular.copy(optionSelectCollection, $scope.optionsSelect);
});
});
So these selected optionsSelect objects are undefined, they stay undefined if nothing is returned and become objects if something is returned. Can you just hide them if they're undefined? Such as in this fiddle...http://jsfiddle.net/LMJXC/40/
<div class="form-group" ng-hide="optionsSelect === undefined">
and
<div class="form-group" ng-hide="optionsSelect2 === undefined">

Resources