Disable button base on the json value - json

so I have a json object and also a edit button. I am wondering how to disable that edit button if the value is not equal to Peter so that the user cannot edit it.
angular.module('app')
.factory('WebApi', function () {
//Dummy Data
var name = [{
value: "Peter",
text: "Peter"
}, {
value: "John",
text: "John"
}, {
value: "Lucy",
text: "Lucy",
}, {
value: "Hawk",
text: "Hawk"
}];
var tempData = [];
//Display 100 item
for (var i = 0; i < 100; i++) {
var selectedName = name[Math.floor((Math.random() * name.length))];
tempData.push({
name: selectedName.text
})
};
constants.js
angular.module('app')
.factory('Constants', function () {
return {
status: {
Peter: 'Peter'
}
};
});
button
<ion-list can-swipe="listCanSwipe">
<ion-item ng-repeat="data in tempData"
item="data">
Name: {{data.name}}
<ion-option-button class="button-calm"
ng-click="edit(data)">
Edit
</ion-option-button>
</ion-item>
</ion-list>

Use ng-disabled:
Examlpe:-
<ion-option-button ng-disabled="name.value!='peter'" class="button-calm"ng-click="edit(data)">
Edit
</ion-option-button>

Use ng-disabled like following
<ion-option-button ng-disabled="data.name!='peter'" class="button-calm"ng-click="edit(data)">
Edit
</ion-option-button>
For reference - https://docs.angularjs.org/api/ng/directive/ngDisabled

In Html
ng-disabled="someFunction()"
In your JS
$scope.someFunction = function() {
// return true or false.
};

Related

Mat select filter for object Array

I want to introduce a search option in my mat-select DropDown.I went through a lot of similar working options, but those are not working for me because of the object array I am passing to the Dropdown. any help is appreciated. thank you.
My Code
HTML File
<mat-form-field>
<mat-select (selectionChange)="getSubtier($event.value)">
<input (keyup)="onKey($event.target.value)">
<mat-option>None</mat-option>
<mat-option *ngFor="let state of selectedStates" [value]="state">{{state.name}}</mat-option>
</mat-select>
</mat-form-field>
TS File
states: string[] = [
{
toptier_agency_id: 15,
create_date: 1517428376464,
update_date: 1560547998012,
toptier_code: "013",
abbreviation: "DOC",
name: "Department of Commerce",
website: "https://www.commerce.gov/",
mapped_org_name: "COMMERCE, DEPARTMENT OF",
display_yn: "Y"
},
{
toptier_agency_id: 16,
create_date: 1517428376787,
update_date: 1560547999157,
toptier_code: "014",
abbreviation: "DOI",
name: "Department of the Interior",
website: "https://www.doi.gov/",
mapped_org_name: "INTERIOR, DEPARTMENT OF THE",
display_yn: "Y"
}];
selectedValue: string;
selectedStates = [];
ngOnInit() {
this.selectedStates = this.states;
}
onKey(value) {
this.selectedStates = this.search(value);
}
getSubtier(value) {
console.log(value);
}
search(value: string) {
// this.selectedStates=[]
// let filter = value.toLowerCase();
// this.selectedStates = this.selectedStates['name'].filter((unit) => unit.label.indexOf(value) > -1);
}
StackBliz Demo
Modify search functuon. Use filter and includes
Try like this:
onKey(value) {
this.selectedStates = this.search(value);
}
search(value: string) {
let filter = this.states.filter(item =>
item.name.toLowerCase().includes(value.toLowerCase())
);
return [...filter];
}
Working Demo
Try the following:
introduce filter with an isVisible property
search(value: string) {
return this.selectedStates.map(k => ({...k, isVisible:(k.name.toLowerCase().indexOf(value.toLowerCase()) > -1)}))
}
add a getter for the filtered state
get filteredState() {
return this.selectedStates.filter(k=> k.isVisible === undefined || k.isVisible)
}
then in your html replace selectedStates with filteredState
<mat-option *ngFor="let state of filteredState" [value]="state">{{state.name}}</mat-option>
TS Note: that you should replace states: string[] with states: any[] or with the object you are using

Uncaught ReferenceError: goAndFind is not defined at HTMLInputElement.onclick

i think i am doing everything fine but still i am getting this error. anybody please guide me through. i have two functions in my javascript file first is myfunction and second is goAndFind but first is working fine on ng-change but both function doesnt work onclick on a button :
this is my javascript file
/// <reference path="angular.min.js"/>
// Initialize Firebase
var config = {
apiKey: "AIzaSyDTTDn-oR0XadcSwllwUkukrw86eH2Ch0g",
authDomain: "mvprecovery.firebaseapp.com",
databaseURL: "https://mvprecovery.firebaseio.com",
storageBucket: "mvprecovery.appspot.com",
messagingSenderId: "119468568560"
};
firebase.initializeApp(config);
var myapp = angular
.module("mymodule", ['firebase'])
.controller("mycontroller", function ($scope , $firebaseObject) {
$scope.selectState;
$scope.findTreatment = findTreatment;
$scope.selectState = selectState;
$scope.selectedInsurance = selectedInsurance;
$scope.goAndFind = function writeUserData() {
firebase.database().ref('tempdata/' + userId).set({
insurance: $scope.selectedInsurance,
state: $scope.selectState,
treatment: $scope.findTreatment
});
};
$scope.myfunction = function () {
if ($scope.selectState == "Pennsylvania") {
$scope.insurance = [
{ name: "Ford Mustang" },
{ name: "Fiat 500" },
{ name: "Volvo XC90" }
];
} else if ($scope.selectState == "new-jersey") {
$scope.insurance = [
{ name: "lahore" },
{ name: "kamalia" },
{ name: "bingokml" }
];
}
};
});
and this is my button code that is clicked
<input type="button" class="btn-success" id="findTreatment" value="Find Treatment" ng-disabled="myform.$invalid && myform.insurancefield.$invalid" onclick="goAndFind()" />
Use ng-click instead of onclick since you're using angular.
<input type="button" class="btn-success" id="findTreatment" value="Find Treatment" ng-disabled="myform.$invalid && myform.insurancefield.$invalid" ng-click="goAndFind()" />
Also, consider giving your functions a clearer name (e.g., setInsurance instead of myfunction). That will help you later on.

AngularJS Filter Select array

I have a select that looks like this
<select
class="form-control"
ng-model="vm.transaction.location_from"
ng-options="l.name for l in vm.locations">
</select>
with vm.locations sourcing from the following JSON:
[
{
"id": "c0d916d7-caea-42f9-a87f-a3a1f318f35e",
"name": "Location 1"
},
{
"id": "d8a299a3-7f4b-4d32-884f-efe25af3b4d2",
"name": "Location 2"
}
]
Further, I have another select that looks like:
<select
class="form-control"
ng-model="vm.transaction.item"
ng-options="i.name for i in vm.items">
</select>
with vm.items sourcing from the following JSON:
[
{
"id": "9f582e58-45dd-4341-97a6-82fe637d769e",
"name": "20oz Soft Drink Cup",
"locations": [
{
"inventory_id": "9d5aa667-4a64-4317-a890-9b9291799b11",
"location_id": "c0d916d7-caea-42f9-a87f-a3a1f318f35e"
},
{
"inventory_id": "9d5aa667-4a64-4317-a890-9b9291799b11",
"location_id": "d8a299a3-7f4b-4d32-884f-efe25af3b4d2"
}
],
}
]
I want to, on change of the ng-mode="vm.transaction.item" select, have the ng-model="vm.transaction.location_from" be filtered to only show values that match from the locations array. I know I can use a | filter: { }, but I'm not sure what that filter should look like.
Hope this is your expected results.
Below are two options I tried ... demo | http://embed.plnkr.co/689OQztgu8F800YjBB2L/
Ref : underscorejs | angular-filter | everything-about-custom-filters-in-angular-js
// 1. filter items collection by location
angular.module('demo').filter('withLocation', function () {
return function (items, selectedLocation) {
function isLocationInLocations (elem) { return selectedLocation && elem.location_id === selectedLocation.id; }
function itemHasLocation (elm){ return (elm.locations && elm.locations.filter(isLocationInLocations).length > 0); }
return items.filter(itemHasLocation);
}});
// 2. filter function to check if option can be rendered ....
vm._filters.selectableItems = function(selectedLocation) {
return function(item) {
var locationsHasLocation = function(elem) { return selectedLocation && elem.location_id === selectedLocation.id; }
return (item.locations && item.locations.filter(locationsHasLocation).length > 0);
}
}
var app = angular.module("Test", []);
app.controller("Ctrl1", function($scope) {
$scope.location_fromArr =
[{
"id": "9f582e58-45dd-4341-97a6-82fe637d769e",
"name": "20oz Soft Drink Cup",
"locations": [{
"inventory_id": "9d5aa667-4a64-4317-a890-9b9291799b11",
"location_id": "c0d916d7-caea-42f9-a87f-a3a1f318f35e"
},{
"inventory_id": "9d5aa667-4a64-4317-a890-9b9291799b11",
"location_id": "d8a299a3-7f4b-4d32-884f-efe25af3b4d2"
}],
}];
$scope.itemArr =
[{
"id": "c0d916d7-caea-42f9-a87f-a3a1f318f35e",
"name": "Location 1"
},{
"id": "d8a299a3-7f4b-4d32-884f-efe25af3b4d2",
"name": "Location 2"
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="Test" ng-controller="Ctrl1">
Item
<select
class="form-control"
ng-model="item"
ng-options="i.name for i in itemArr">
</select>
Location
<select
class="form-control"
ng-model="location_from"
ng-options="l.name for l in location_fromArr | filter:{l.id: location_from.location_id}">
</select>
</div>
One way to do this is to supply a filter function to filter the locations. Something like:
vm.filterFun = function(selectedLocations) {
return function (location) {
var n;
if (!selectedLocations) {
return true;
}
for(n=0;n<selectedLocations.length;n += 1) {
if (selectedLocations[n].location_id === location.id) {
return true;
}
}
return false;
}
}
This is actually a function returning a filter function, based on the item selected.
Then in your select you apply the filter with:
<select
class="form-control"
ng-model="vm.transaction.location_from"
ng-options="l as l.name for l in vm.locations | filter:vm.filterFun(vm.transaction.item.locations)">
</select>
See plunker here.
I would forego angular filters and use the getterSetter option of ngModelOptions.
It could look something like this:
var selectedItem, selectedLocation;
var items = [];
var locations = [];
vm._items = items; // Static, always allow all items to be selected.
vm.locations = function () {
// Return differing results based on selectedItem.locations.
};
vm._transaction = {
location: function (v) {
/**
* If v is null, it is not present in the selectedItem.locations array.
* The extra check will ensure that we don't persist a filtered out location when
* selecting another item.
*/
return (v || v === null) ? (selectedLocation = v) : selectedLocation;
},
item: function (v) {
return v ? (selectedItem = v) : selectedItem;
}
};
Here's a plunker demonstrating the behaviour.
Not as simple/straight-forward as a filter, but I would bet (at least in the case of a piped filter) that you'd possibly see a slight performance gain going with this approach.
I do not have numbers to back up the above statement, and it usually boils down to the size of your dataset anyway. Grain of salt.
If you need it to function the other way around, you could write up a secondary filter like such:
function superFilter2 (arr) {
// If no location is selected, we can safely return the entire set.
if (!selectedLocation) {
return arr;
}
// Grab the current location ID.
var id = selectedLocation.id;
// Return the items that are present in the selected location.
return arr.filter(function (item) {
return item.locations.map(function (l) {
return l.location_id;
}).indexOf(id);
});
}
With that and the filter in the supplied plunker, there are some similarities that could be moved into higher order functions. Eventually with some functional sauce you could probably end up with a single god function that would work both ways.
you can do this:
<select
class="form-control"
ng-model="vm.transaction.item"
ng-change="itemCahngedFn()"
ng-options="i.name for i in vm.items">
</select>
var itemChangedFn = function(){
var filtredItems = [];
angular.forEach(vm.locations, function(item){
if(item.name == vm.transaction.item){
filtredItems .push(item.location);
}
});
vm.locations= filtredItems ;
}
i think filter:{ id : item.locations[0].location_id } should do the trick.
here is the jsfiddle
how do you think?

ng-init json Object

I use angularjs (ng-init) and I want to assign value to variable as jsonObj.
I try this one but it doesn't work.
ng-init="percentObj = [{ "value":40,"color":"#F5A623" },{ "value":60,"color":"#F5A623" }];
and another question
I want to assign value like
percentObj = [{ "value": parseInt($scope.projectData[0].value),"color":"#F5A623" },{ "value": parseInt($scope.projectData[0].value),"color":"#F5A623" }]
How to fix this problem??
Thx
You can use window object for set your json :
<script type="text/javascript">
window.data= {awesome:1};
</script>
view :
<div ng-controller="myCntrl" ng-init="init('data')">
controller :
function myCntrl($scope) {
$scope.init = function (settings) {
settings = window[settings];
console.log(settings.awesome); //1
};
}
Escape your quotes...
ng-init="percentObj = [{ \"value\":40,\"color\":\"#F5A623\" },{ \"value\":60,\"color\":\"#F5A623\" }];"
Try this...
<body ng-controller="TestController">
<div ng-init="Init()">
{{percentObj || json }}
</div>
</body>
$scope.Init = function()
{
$scope.percentObj = [{ "value":40,"color":"#F5A623" },{ "value":60,"color":"#F5A623" }]
}
Just have a JSON encoded string in some element's attribute and then catch that with Angular.
HTML
<div data-config="{title:'this is my title'}" my-directive></div>
AngularJS:
app.directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element) {
// apply config from element's data-config attribute
scope.config = element.data('config');
// print out the data in console
console.log(scope.config);
}
};
});
Can be done without jQuery too, then the .data('config') part changes.
for second one, Please check the code below
var obj = {};
$scope.percentObj = [];
obj.value = parseInt($scope.projectData[0].value);
obj.color = "#F5A623";
$scope.percentObj.push(obj);

How to add a tooltip based on a DropDown list

Basically I have a Kendo Grid where a couple of my columns also have Kendo DropDowns.
I would like to attach a ToolTip based on the value the user chooses from the "Instrument" dropdown.
Here's my grid javascript code (using MVVM pattern):
tradesGrid = $("#tradesGrid").kendoGrid({
dataSource: datasource,
toolbar: [
{ name: "create", text: "Add Trade" }
],
columns: [{
field: "TradeId"
},
{
field: "Instrument",
editor: instrumentsDropDownEditor, template: "#=Instrument#"
},
{ command: ["edit", "destroy"] },
],
sortable: true,
editable: "popup",
});
and here's the Editor function for the Instrument dropdown :
function instrumentsDropDownEditor(container, options) {
var instrItems = [{
"optionInstr": "OPTION 22/11/2013 C70 Equity"
}, {
"optionInstr": "OPTION 26/11/2013 C55 Equity"
},
{
"optionInstr": "OPTION 30/11/2013 C80 Equity"
}
];
var input = $('<input id="Instrument" name="Instrument">');
input.appendTo(container);
input.kendoDropDownList({
dataTextField: "optionInstr",
dataValueField: "optionInstr",
dataSource: instrItems, // bind it to the brands array
optionLabel: "Choose an instrument"
}).appendTo(container);
}
and on my Html view file I'm starting with this idea :
<span class="key-button"
title="Instrument Details!!!"
data-role="tooltip"
data-auto-hide="true"
data-position="right"
data-bind="events: { show: onShow, hide: onHide }"
</span>
I don't have time to rig up a jsFiddle right now, but I'm pretty sure this would work...
Init your tooltip in javascript, and specify content that is a function:
var myTooltip = "";
var tooltipWidget = $("#whatever").kendoTooltip({
filter: "a",
content: function (item) { return myTooltip; },
...
}).data("kendoTooltip");
Then on your dropdown widget, specify a change function handler that sets myTooltip to whatever contents you want.
var onSelect = function (e) {
myTooltip = ...;
tooltipWidget.refresh();
};
$("#dropdownlist").kendoDropDownList({
select: onSelect,
...
});
Or you can change the title property on your HTML element, if that is easier. However, the tooltip widget won't refresh its contents after it has been displayed, which is why you need to manually call tooltipWidget.refresh() after you change the contents.