Have radios in one controller hide/show an element in another controller - javascript

I am trying to connect some functionality between controllers. Basically I want a div to hide/show based on what radio is selected in a different controller.
With a little help I managed to get this working part of the way. Here's what I have so far.
I set up a factory to bridge communication between the 2 controllers where I have an update function that is fired upon ng-change to update the string with the new desired one.
.factory("sessionCheck", function() {
var sessionCheck = {};
var update = function (index) {
console.log(index);
sessionCheck = index;
return sessionCheck;
};
return { update: update }
So in the first controller will call the function when ng-change occurs on the radios, like so:
//bring in session check, (injected above)
$scope.updateChecker = sessionCheck;
$scope.sessionChange = function(){
$scope.updateChecker.update($scope.opMeasure);
};
So this works fine if I console.log the index in the change function in the factory. So where I'm struggling is pulling this information into another controller and using it to ng-hide (or show) a div.
It would also be cool if there was a default value of "1" returning before the ng-change fired. It would be even better if there is an easier way that directly reads off of the radios' model (opMeasure) instead of firing off the ng-change of the radios.
Been struggling with this for a few hours, any help would be much appreciated. Thanks!!

I have answered a similar question yesterday. You can do this by sharing a common data object reference across your controllers using a common service.
DEMO
JAVASCRIPT
angular.module('demo', [])
.factory('SessionCheck', function() {
var sessionCheck = {
data: {}
};
// default value
sessionCheck.data.selection = 1;
return sessionCheck;
})
.controller('Ctrl1', function($scope, SessionCheck) {
$scope.data = SessionCheck.data;
})
.controller('Ctrl2', function($scope, SessionCheck) {
$scope.data = SessionCheck.data;
});
HTML
<div ng-controller="Ctrl1">
<h1>Controller 1</h1>
Measurement:
<select ng-model="data.selection">
<option value="">-- Select</option>
<option value="1">1 Meter</option>
<option value="2">2 Meters</option>
<option value="3">3 Meters</option>
</select>
</div>
<div ng-controller="Ctrl2">
<h1>Controller 2</h1>
<div ng-show="data.selection == 1">
1 Meter items
</div>
<div ng-show="data.selection == 2">
2 Meter items
</div>
<div ng-show="data.selection == 3">
3 Meter items
</div>
</div>

Related

Implementing multiselect dropdown in angular js

I am trying to implement a multiselect dropdown in AngularJS and trying to store the values in an list in my JS file. However I am unable to handle the event for selecting multiple values.
I have used ng-change but this handles only one click. Selecting multiple values using CTRL + arrow key is not handled. My list is dynamically generated.
Please suggest ways to handle it using Javascript/AngularJS
<div>
<select multiple class="form-control drop-down" name="abclist" id="users" ng-model="databaseUser" ng-options="databaseUser.username for databaseUser in databaseUsers" ng-change="ctrl.onchange()" required>
<option value="" >SELECT USER VALUE</option>
</select>
</div>
(function () {
'use strict';
angular.module(userdetails.module).controller('UserController', UserController);
UserController.$inject = ['$scope', '$rootScope','$http', 'dData', '$location', '$uibModal'];
function AdminController($scope, $rootScope, $http, dData, $location, $uibModal) {
function onchange(){
}
You don't need to catch the onChange event to do that, the ng-model attribute will do the work for you.
HTML
<div ng-app="myModule">
<div ng-controller="myController as ctrl">
<div>
<p>Selected users: {{ctrl.selectedUsers}}</p>
<select multiple
id="users"
ng-model="ctrl.selectedUsers"
ng-options="user as user.label for user in ctrl.users track by user.id">
</select>
</div>
</div>
</div>
Javascript
var module = angular.module("myModule", []);
module.controller("myController", function() {
var $ctrl = this;
$ctrl.users = [{id:1, label:'eyp'}, {id:2, label:'jrt'}];
$ctrl.selectedUsers = null;
});
Here you have a JSFiddle test to show you how it works.

show ionic loader in between the process of ng-repeat rendering data

This question my seems silly to you but i just want to know that is it possible to show ionic loader in between the process of rendering data in dropdown by ng-repeat.I goggled and found two directives one is for after-render and other is for on-finish-render both works good but i am really confused that how can i show and hide my ionic loader during this whole process.
here is some of my code :-
<label class="item item-input"> <select class="input-select"
ng-model="user.country.value"
ng-change="selectedCountry(user.country.value)">
<option ng-selected="country.value==user.country.value"
ng-repeat="country in results" value="{{country.value}}">
{{country.name}}</option>
<option value="" disabled hidden>{{'checkoutPage.country' |
translate}}</option>
</select>
</label>
<label class="item item-input" ng-if="showDropDownInStateLabel()">
<select class="input-select" ng-model="userState.states.region_id"
ng-change="selectedState(userState.states.region_id)">
<option ng-selected="states.region_id==userState.states.region_id" ng-repeat="states in StatesArray" on-finish-render="ngRepeatFinished"
value="{{states}}">{{states.name}}</option>
<option value="" disabled hidden>{{'checkoutPage.state' |
translate}}</option>
</select>
</label>
here is directive :-
app.directive('onFinishRender', function($timeout) {
return {
restrict : 'A',
link : function(scope, element, attr) {
if (scope.$last === true) {
$timeout(function() {
scope.$emit('ngRepeatFinished');
});
}
}
}
});
here is the listener for event:-
$scope.$on('ngRepeatFinished', function(
ngRepeatFinishedEvent) {
alert("rendering ends here");
});
can any one tell me that how to show loader to user when ng-repeat rendering the data in dropdown.I even try by making two different functions for showloader() and hideloader() . showLoader i call when user select some value in dropdown and hideLoader gets call in $scope.$on function.
Actually i am having two dropdowns one is for countries and other is for their respective states.When user select country that state dropdown got visible to user.this whole process took some time in rendering which make application looks like hanged to user so i just want to display user a loader to avoid this illusion.
here is the function which finds which country have states array and according to which stats dropdown got visible to user :-
$scope.user = {};
$scope.selectedCountry = function(value) {
// alert(value);
$scope.data.region = '';
if (angular.isString(LocalStorage
.getData("StateSelected"))) {
LocalStorage.setData("StateSelected", "");
LocalStorage.setData("Statename", "");
}
if (angular.isString(LocalStorage
.getData("Addressregion"))) {
LocalStorage.setData("Addressregion", "");
}
$scope.user.country_id = value;
LocalStorage.setData("CountrySelected", value);
for ( var c = 0; c < LocalStorage
.getObject("getCountriesresult").length; c++) {
if (value == LocalStorage
.getObject("getCountriesresult")[c].value) {
if (LocalStorage
.getObject("getCountriesresult")[c].state.length > 0) {
shouldShowDropdown = true;
$scope.StatesArray = LocalStorage
.getObject("getCountriesresult")[c].state;
} else {
shouldShowDropdown = false;
}
}
}
}
Any help will be appreciated,
Thanks
This kind of feature should never take so long to execute.
I think you should try to remove the huge amount of LocalStorage access inside loops. From what I saw, you can do everything you want using local variables (in-memory).
$ionicLoading works fine for async calls that take time, like an AJAX call.

Set selected value of select menus

I have three select menu that bind to each other and want to set selected value of two select menus. Value that I want to set comes with scope. I try ng-init but that didn't work. Working Plunker
<select ng-init="selManga=direk" ng-model="selManga" ng-options="manga.seri for manga in mangas">
<option value="">Select a Manga</option>
</select>
<select ng-init="selChapter=bacanak" ng-show="selManga" class="browser-default" ng-model="selChapter" ng-options="+idx as chapter.klasor for (idx, chapter) in selManga.randomword">
<option value="">Chapter</option>
</select>
<select ng-show="selManga.randomword[selChapter].yol" class="browser-default" ng-model="selPage" ng-options="+idx as (+idx + 1) for (idx, page) in selManga.randomword[selChapter].yol">
<option value="">Page</option>
</select>
Javascript:
.controller('nbgCtrl',function ($scope, MMG, $stateParams) {
$scope.direk = $stateParams.seri;
$scope.bacanak = $stateParams.klasor;
MMG.adlar.success(function(loHemen) {
$scope.mangas = loHemen;
});
$scope.next = function (manga, chapter, page) {
var nextPage = page + 1;
if (angular.isDefined(manga.randomword[chapter].yol[nextPage])) {
$scope.selPage = nextPage;
} else if (angular.isDefined(manga.randomword[chapter + 1])) {
$scope.selChapter = chapter + 1;
$scope.selPage = 0;
}
}
})
To extract the values for the manga,chapter and page from the url you should use the $routeParams object, which your module should include ngRoute.
I've prepared an example here it might not be obvious but if you download the code and run it in your own browser you can access routes like Manga/Naruto/ch/100 from the url bar.
Once you've restructured your application to use routes and routeParams, in my example I directly bind the chapter and page I get from the url to the view but if you bind them to the models of your dropdowns the dropdowns will update.
$scope.params = $routeParams;
$scope.selManga = $scope.params.bookId
This does not update the url as you select from the dropdown.
In your code you have assign direk and bacanak value more than one times which can cause issue. Set variable property only once.
$scope.direk = $stateParams.seri;
$scope.bacanak = $stateParams.klasor;
$scope.direk = $stateParams.xy; //Remove if not required
$scope.bacanak = $stateParams.xz; //Remove if not required
Set selManga value from $stateParams instead of setting it to direk
$scope.selManga = $stateParams.seri; // Set selManga from $stateParams
$scope.selChapter = $stateParams.klasor; // Set selChapter from $stateParams
The reason why ng-init="selManga=direk" not work is because Syntax error: ng-init="selManga=direk" should be ng-init="selManga='direk'" but after making syntax correct, dropdown will not set because of ng-repeat. ng-init set value to model but at time of setting value ng-repeat doesn't complete setting value for options so selManga set from ng-init not update option to dropdown.

Angularjs Dropdown won't hold value after refresh

I have been working on this way too long trying to figure it out.
<select class="form-control"
ng-model="question.sel"
ng-change="updateDropDownQuestion(question,question.sel)">
<option ng-repeat="answer in question.answers" ng-disabled="answer.notAnOption" value="{{answer.acode}}">{{answer.name}}</option>
<option style="display:none" value="NONE">NONE</option>
</select>
Then in my js file:
$scope.updateDropDownQuestion = function(question, answer) {
reset(question.code)
$scope.formData["SOLE/SELECTED_QUESTION"] = question.code
$scope.formData["SOLE/SELECTED_ANSWER"] = answer
$scope.formData[question.code+"/"+answer] = true
var questions = $scope.product.questions
for(i=0; i <questions.length;i++){
if(questions[i].code == question.code){
questions[i].sel = answer
break;
}
}
$scope.refresh()
};
the $scope.refresh() is where it changes back. This renders the screen.
no matter what I do it seems to render the previous state and not the current state of the drop down. This is because I am repainting the screen after the drop down changes.
It seems as though the when the screen repaints it is taking the original value first.
Any thoughts on how I can get the value to "stick" once set?
Do I need to fire some event afterwards?
From Angular official site:
Note: ngModel compares by reference, not value. This is important when binding to an array of objects. You might find this helpful to set the default values of your drop down. See an example below.
angular.module('demoApp', []).controller('DemoController', function($scope) {
$scope.options = [
{ label: 'one', value: 1 },
{ label: 'two', value: 2 }
];
// Although this object has the same properties as the one in $scope.options,
// Angular considers them different because it compares based on reference
$scope.incorrectlySelected = { label: 'two', value: 2 };
// Here we are referencing the same object, so Angular inits the select box correctly
$scope.correctlySelected = $scope.options[1];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="demoApp">
<div ng-controller="DemoController">
<div>
<h2>Incorrect</h2>
<p>We might expect the select box to be initialized to "two," but it isn't because these are two different objects.</p>
<select ng-model="incorrectlySelected"
ng-options="opt as opt.label for opt in options">
</select>
The value selected is {{ incorrectlySelected.value }}.
</div>
<div>
<h2>Correct</h2>
<p>Here we are referencing the same object in <code>$scope.correctlySelected</code> as in <code>$scope.options</code>, so the select box is initialized correctly.</p>
<select ng-model="correctlySelected"
ng-options="opt as opt.label for opt in options">
</select>
The value selected is {{ correctlySelected.value }}.
</div>
</div>
</body>
Try using ng-options to render option elements.
Something along these lines:
<select class="form-control"
ng-model="question.sel"
ng-change="updateDropDownQuestion(question,question.sel)"
ng-options="answer.acode as answer.name in question.answers">
</select>
It also depends on what updateDropDownQuestion is doing, can you provide that?

calling a HTTP get method to populate the result in drop down using angular JS

I have all controllers defined at one place.
$routeProvider.when(pages.hello,
{
templateUrl: 'test/hello.html',
controller: 'myController',
access: access.anon,
helloPage: 'arf'
});
My hello.html looks like this.
<select name="chooseFunc" data-ng-model="choosenFunction" class="input-xlarge ng-pristine ng-valid" data-ng-click="fetchID()" data-ng-change="update(choosenFunction)">
<option value="ABCD">ABCD</option>
<option value="CDEF">CDEF</option>
</select>
Now I want to call a http get method "/abc/hello" to populate the drop down like ABCD, CDEF values based on it.
I have written some thing like this.
$scope.fetchID = function() {
console.log("hello in fectch id");
$http.get('/abc/hello').success(successCallback).error(error);
};
My function is not getting called. Could some help me with the following.
Calling fecthID() function on page load.
fechID() function should populate the options in select element.
I am new here. Can some one help me.
I would write controller like:
function myController($scope,$http) {
$scope.values = [{id:"ABCD",Name:"David"},{id:"CDEF",Name:"John"}];
$scope.selectedItem = $scope.values[0].id;
$scope.fetchID = function() {
$http.get('/abc/hello').success(
function(data, status, headers, config){
$scope.values.push(data);// play here
})
.error(error);
};
$scope.fetchID(); // call
}
and hello.html with init first combo value:
<select name="chooseFunc"
ng-model="selectedItem"
ng-options="selectedItem.id as selectedItem.id for selectedItem in values"
class="input-xlarge ng-pristine ng-valid"
data-ng-click="fetchID()"
data-ng-change="update(choosenFunction)"
></select>
You can use ng-options to populate select like
<select ng-model="mySelecetdValue" ng-options="item for item in items">
</select>
To Call fecthID(), Just call it like
$scope.fetchID()
And Populate items in successCallback function

Categories

Resources