Angularjs two way data binding - ngChange - angularjs

I am working on a project which is having a web form using html and angularjs
the backend using java/spring and db oracle.
My form contains few lists say list1,list2...
list1 get its items from db. As soon as user selects the item in list1 ng-change gets trigger and data for list2 geenrates.That means list2 values depends on list1 ng-change directive.After filling all required fields I am saving the form in db.
Now I am giving user a provison that they can see there filled details . So once they click on "edit" they can see all their details. I am using ng-model to bind the data .All fields are working and binding values form db to the html webform except for list2. Can anyone show how can we achieve this.
I am having some issues with hide/show functionality when user wants to see his request in editable mode. Please suggest some workaround.
<div ng-app="myApp" ng-controller="myCtrl">
<label>List1:</label>
<select ng-model="selectedName" ng-change="getList()" ng-options="item for item in names">
</select>
<br>
<label>List2:</label>
<select ng-model="selectedNcomany" ng-options="item for item in comany">
</select>
<button ng-click="editText()">
Edit
</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
var db = {};
$scope.getList = function(){
if($scope.selectedName == "Linus"){
$scope.comany = ["!","2"];
}
else{
$scope.comany =["0"]
}
}
$scope.editText = function(){
$scope.selectedName = "Linus";
$scope.selectedNcomany = "1";
}
});
</script>
https://jsfiddle.net/31d8cv92/12/

I work in the similar environment we created a service show field which looks like this
angular.module('test').service('showField',showField);
function showField(){
this.showfield = function(fieldData,pagemode){
if(angular.isDefined(fieldData) && fieldData.hasOwnProperty('hide')){
if (fieldData.hide) {
if (fieldData.npi) {
if (pagemode == 'view') {
return false;
}else {
return true;
}
} else {
return false;
}
} else {
return true;
}
}
}
}
We invoke this in our required controllers for view mode and update mode.
**(New to AngularJS)

Related

Dynamically adding multiple custom directives associated with single controller in angularjs 1

I have an html template attached to a controller and three directives. There are three buttons. On clicking a button a directive is added to the page(using ng-click) like this(the following is in my controller not in directive):
$scope.addFilterDimension = function() {
console.log('CLICKED!!!!!!!')
var divElement = angular.element(document.querySelector('#filterDimension'));
var appendHtml = $compile('<filter-directive></filter-directive>')($scope);
divElement.append(appendHtml);
}
Similarly for other buttons, other directives are added. Now, I can keep adding as many of these directives as I like, which is the use case here.
These directives are basically like forms containing either dropdowns, input boxes or both. The values user selects from the dropdowns or enters in input boxes have to be sent back to the backend to be stored in the DB.
This is one of the directives(others are very similar):
anomalyApp.directive('filterDirective', function() {
return {
restrict: "E",
scope: {},
templateUrl:'filter-dimension.html',
controller: function($rootScope, $scope, $element) {
$scope.dimensionsOld = $rootScope.dimensionsOld;
$scope.dimensions = $rootScope.dimensions;
$scope.selectedDimensionName = $rootScope.selectedDimensionName;
$scope.selectedDimensionValue = $rootScope.selectedDimensionValue;
$scope.extend = $rootScope.extend;
$scope.selectedExtend = $rootScope.selectedExtend;
$scope.isDateField = $rootScope.isDateField;
console.log($scope.dimensions);
$scope.Delete = function(e) {
//remove element and also destoy the scope that element
$element.remove();
$scope.$destroy();
}
}
}
});
Now, in my controller I assign $rootscope to my values which have to be used in the directives and thus catch them in the directive. Example:
$rootScope.dimensions = temp.map(d=>d.dimName);
$rootScope.selectedDimensionName = '';
$rootScope.selectedDimensionValue = '';
And this is how I retrieve my values from added directives:
var retriveValue = function() {
var filtersData = [];
var constraintsData = [];
var variablesData = [];
var ChildHeads = [$scope.$$childHead];
var currentScope;
while (ChildHeads.length) {
currentScope = ChildHeads.shift();
while (currentScope) {
if (currentScope.dimensions !== undefined){
filtersData.push({
filterDimensionName: currentScope.selectedDimensionName,
filterDimensionValue: currentScope.selectedDimensionValue,
filterDimensionExtend: currentScope.selectedExtend,
filterDimensionIsDateFiled: currentScope.isDateField
});
}
if (currentScope.constraintDimensions !== undefined){
filtersData.push({
constraintDimensionName: currentScope.selectedConstraintName,
constraintDimensionValue: currentScope.selectedConstraintValue,
constraintDimensionExtend: currentScope.selectedConstraintExtend,
constraintDimensionVariable: currentScope.selectedConstraintVariable,
constraintDimensionOperator: currentScope.selectedOperator,
constraintDimensionVariableValue: currentScope.constraintVariableValue,
constraintDimensionIsDateField: currentScope.isDateFieldConstraint
});
}
if (currentScope.variableNames !== undefined){
console.log('currentScope.selectedVariableVariable',currentScope.selectedVariableVariable);
filtersData.push({
variableName: currentScope.selectedVariableVariable,
variableOperator: currentScope.selectedVariableOperator,
variableValue: currentScope.variableVariableValue,
variableExtend: currentScope.selectedVariableExtend
});
}
currentScope = currentScope.$$nextSibling;
}
}
return filtersData;
}
This is one of the directive's template:
<div >
<div>
<label>Dimension</label>
<select class = "custom-select custom-select-lg mb-6" ng-model="selectedDimensionName" ng-options="dimension for dimension in dimensions">
<!-- <option ng-repeat="table in tables track by $index">{{table}}</option> -->
</select>
</div>
<div>
<label>Date Field</label>
<input type="checkbox" ng-model="isDateField">
</div>
<div>
<label>Value</label>
<select multiple class = "custom-select custom-select-lg mb-6" ng-model="selectedDimensionValue" ng-options="val for val in ((dimensionsOld | filter:{'dimName':selectedDimensionName})[0].dimValues)"></select>
</span>
</div>
<div>
<label>Extend</label>
<select class = "custom-select custom-select-lg mb-6" ng-model="selectedExtend" ng-options="val for val in extend"></select>
</span>
</div>
<button type="button" class="btn btn-danger btn-lg" ng-click="Delete($event)">Delete</button>
This is in the main html to add the directive:
<div id="filterDimension"> </div>
I know this is not a good way, but please suggest a better one.
Secondly, a new change has to be made where inside one of the directives there will be a button, clicking on which 2 dropdowns(or simply one more directive) will be added and can be added as many times as needed(just like the other directive).
The issue here is this one is a directive inside another directive and I am facing unusual behavior like:
When I add the parent directive it is fine, I add the child directives its fine, but when I add a second parent and try to add its child, they get appended inside the first directive.
Even if I somehow manage to get out of the above point I do not know how to retrieve values from such directives.
PS: I am new in AngularJS or front-end for that matter, the retriveValue() and using rootscope I got from somewhere online.

Store the value of selection from dropdown to a variable AngularJS

I would like to store the value of a selection from a dropdown in AngularJS.
I am able to replicate the new selection on UI but not in console.
<div ng-controller="MyCtrl">
<div>
Fruit List:
<select id="fruitsList"
ng-model="cart"
ng-change="getSelectedLocation()"
ng-options="state for state in shelf"></select>
<br/>
<tt>Fruit selected: {{cart}}</tt>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.cart = "";
$scope.shelf = ['Banana', 'Apple', 'Pineapple', 'Blueberry'];
$scope.getSelectedLocation = function() {
console.log($scope.cart);
}
$scope.printSelectedValue = function() {
if ($scope.cart == 'Banana') {
console.log("Its a banana")
} else if ($scope.cart == "Apple") {
console.log("Its an apple")
} else {
console.log("Its neither a banana nor an apple")
}
}
});
Any idea on how to achieve that?
jsfiddle link
You're printing the cart once, when the controller is instanciated. At that time, the user hasn't had the chance to select anything yet.
If you want to print the selection every time it changes, use ng-change (you're already using it, BTW):
ng-change="printSelection()"
and in the controller:
$scope.printSelection = function() {
console.log($scope.cart);
};

Retain the dropdown value after the page is refresh or move to another page in angularjs

let me explain my scenario. I am having the dropdownlist in my master page. if changed dropdownlist the data are changed depend upon the dropdownlist value.
If i refreshed my page or moved to another page the dropdownlist will clear automatically.
I want to retain the dropdownlist value after refresh the page or moved to another page.
I tried like this but this is not help ful.
HTML
<select id="Facility_ID" required typeof="text" name="Facility Name" ng-options="Role.FacilityName for Role in Roles"
form="DistanceMatrixFormId" class="form-control" ng-model="Role._id" ng-selected="getFacilityID(Role._id.FacilityName)">
</select>
Controller.js
$scope.getFacilityID = function (data) {
localStorage.setItem("FacilityName", data);
var getfacility = localStorage.getItem("FacilityName");
}
i refered this link but it is not help ful
I don't know how to retain the value. can any one fixed me.
You cannot put an object into the local storage, you must store strings inside local storage.
If you want, you can have an implementation I did here : How to add local storage in angular?
For your current code, you don't need to use ng-selected. ng-model is enough.
<select id="Facility_ID" required typeof="text"
name="Facility Name"
ng-options="Role.FacilityName for Role in Roles"
form="DistanceMatrixFormId"
class="form-control"
ng-model="Role._id"
ng-change="updateLocalStorage()">
</select>
And inside your angular controller, what you can do is the following :
myApp.controller('controllerName', ['$scope', 'LocalStorageService',
function($scope, LocalStorageService){
// After initialization of your "Role" object
$scope.Role._id = LocalStorageService.retrieve('mySelectValue');
$scope.updateLocalStorage = function(){
LocalStorageService.store('mySelectValue', $scope.Role._id);
}
}])
Here is an example that uses a service to store the selected value. Unfortunately the embedded demo does not work because of the sandboxing, but works when served as an application.
angular.module(
"App", []
).factory("MyStorage", function() {
const key = "selected";
return {
getValue: function() {
const stored = localStorage.getItem(key);
return stored ? JSON.parse(stored) : null;
},
setValue: function(value) {
localStorage.setItem(key, JSON.stringify(value));
}
};
}).controller("MyCtrl", function($scope, MyStorage) {
$scope.options = ["A", "B", "C"];
$scope.selected = MyStorage.getValue();
$scope.$watch("selected", newValue => {
MyStorage.setValue(newValue);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="App" ng-controller="MyCtrl">
<select ng-model="selected" ng-options="x for x in options">
</select>
</div>

Select all elements when all checkboxes unchecked

I am working on a webpage that would display a list of products with several attributes (color, size, style). I would need that when all checkboxes are unchecked, the page would show all the products, and just when I start checking one the categories will it start filtering the products. Is that possible with checklist-model? Thanks in advance
Yes you can use checklist-model (http://vitalets.github.io/checklist-model/ if you are refreeing this)
Have the code below which will tell you how can you do it just add the filtering logic to it.
Controller code
myApp.controller('MyCtrl', function ($scope) {
//On controller load show all the products
$scope.filters = ['color','style','size'];
$scope.allproducts = [];
$scope.selectedFilters = {
filters: []
};
$scope.applyFilter = function (filters)
{
//Add filtering logic to filter objects from allproducts
//according to filter values in the filters array passed in the function.
//the data will be changed in if filter applied to allproducts array as allproducts in binded in view.
}
$scope.$watchCollection('$scope.selectedFilters.filters', function (newVal, oldVal) {
//If all values are unchecked
if($scope.selectedFilters.filters.length == 0)
{
//Show All products
}
else {
//Show the filtered products
applyFilter($scope.selectedFilters.filters) ;
}
}); });
View code:
<div ng-app="MyApp" ng-controller="MyCtrl">
<label ng-repeat="filter in filters">
<input type="checkbox" checklist-model="selectedFilters.filters" checklist-value="filter"> {{filter}}
</label>
<label ng-repeat="product in allproducts">{{product}}</label>
</div>

saving and retrieving saved checkbox values from local storage in angularjs

I am new to angularjs and phonegap. I am trying to build an app where on a page, a user can select a category from say 9 categories. I am putting a checkbox beside each category name for the user to select the categories. After selecting a few categories(by checking the respective checkboxes), the user can press the save button for the categories to be saved. My question is how do I save all those categories and how do I retrieve them?
This is the code I have so far
<!--html code --> <!-- the items here the titles of the categories pulled from a data.js file-->
<div ng-repeat="row in items | partition:3">
<div ng-repeat="item in row"">
<input type="checkbox" ng-model="(item.title)">
<div>{{item.title}}</div>
<ons-button modifier="large" ng-click="savecategories()">Ready</ons-button>
/*angularjs code */
app.controller('categoryController', function($scope) {
$scope.savecategories = function() {
if ($scope.category1)
{
localStorage.setItem('category1', true);
}
else {
localStorage.setItem('category2', false);
if ($scope.category2)
{
localStorage.setItem('category2', true);
}
else {
localStorage.setItem('category2', false);
}
/*and so on */
}
});
I tried to see if it is working by putting this line of code so that I would get an alert but no luck.
var national = localStorage.getItem('category1');
window.alert(national);
I am not sure what I am doing wrong. Any help will be greatly appreciated.
Thank you everyone. I figured it out finally. I just added a function which is called everytime a checkbox is checked or unchecked.
<input type="checkbox" ng-model="item.value" name="item.title" ng-change="savecategories()">
In my js file, I did this:
app.controller('HomeController', function($scope, Data, localStorageService) {
$scope.items = Data.items;
if (localStorageService.get('items')) {
$scope.items = localStorageService.get('items');
}
$scope.SaveCategories = function () {
localStorageService.clearAll();
localStorageService.add('items',$scope.items);
}

Resources