angularjs how to search in search in json object in html template - javascript

In Angularjs I am trying to search in json data which i am using in html template. My input json data is as below,
var data = JSON.parse(
'{
"Project": {
"_attributes": {
"gui": "ProjectGui",
"prjname": "MyProject"
},
"stringarr": [
{
"_attributes": {
"name": "Project.comments"
},
"_text": "MyComments"
},
{
"_attributes": {
"name": "Project.classpath"
},
"_text": "D:\\Project\\bin\\config.jar"
}
]
}
}'
);
And i am using this for displaying and editing name in my html template, which is working fine. When I edit input box , it reflects the changes in json data as well, that's exactly I want.
Name: <input type="text" ng-model="data.Project._attributes.prjname"><br>
But I also want to display and edit comments in same way but not getting idea how to achieve this. The difference is, I have to search within json data where data.Project.stringProp[i]._attributes.name is "Project.comments" and take "_text" as input for displaying & editing. I have tried following that is not working.
Comments: <input type="text" ng-repeat="x in data.Project.stringProp" ng-model="x">{{x._text}}<br>
Please suggest , what would be the best possible way to do this. I think it can be done using a get function and ng-change function but that approach will be lengthy and may put performance overheads.
Thanks

You can either implement a filter for filter _text value if the name is 'Project.comments', or you can simply add an ng-if statement.
Comments: <input type="text" ng-repeat="x in data.Project.stringarr" ng-if="x._attributes.name == 'Project.comments'">{{x._text}}<br>

I have resolved this by using ng-repeat and ng-if for specified condition.
<body ng-controller="Controller">
Name: <input type="text" ng-model="data[0].Project._attributes.prjname"><br>
check: <div ng-repeat="x in data[0].Project.stringarr" ng-if="x._attributes.name == 'Project.comments'">{{x._text}}</div><br><br>
comments : <input type="text" ng-repeat="x in data[0].Project.stringarr" ng-if="x._attributes.name == 'Project.comments'" ng-model="x._text"><br>
</body>
Please find the following plunkr
https://plnkr.co/edit/3jUaw73cHgAtbBZr8LuJ?p=preview

Related

How will i shuffle input form elements in angular 4

I am making an application which will have form with dynamic input elements. With dynamic i mean that those inputs will come from the server side. Here's the psedo sample html :
<form>
<section1>
<static-field-1></static-field-1>
<static-field-2></static-field-2>
<dynamic-field-1></dynamic-field-1>
<dynamic-field-2></dynamic-field-2>
</section1>
<section2>//'a' postfix is just for differenting
<dynamic-field-1a></dynamic-field-1a>
<static-field-1a></static-field-1a>
<static-field-2a></static-field-2a>
<dynamic-field-2a></dynamic-field-2a>
</section2>
</form>
In short all the form rendering including their position will be decided by the api response from the server.
The api response will be something like this:
[
{
"section_pos":1,
"name":"section1",
"fields":[
{
"type":"static",
"name":"static-field-1"
},
{
"type":"static",
"name":"static-field-2"
},
{
"type":"dynamic",
"name":"dynamic-field-1",
"input":"text",
"validation":"required"
},
{
"type":"dynamic",
"name":"dynamic-field-2",
"input":"number",
"validation":"required"
}
]
},
{
"section_pos":2,
"name":"section2",
"fields":[
{
"type":"dynamic",
"name":"dynamic-field-1a",
"input":"text",
"validation":"required"
},
{
"type":"static",
"name":"static-field-1a"
},
{
"type":"static",
"name":"static-field-2a"
},
{
"type":"dynamic",
"name":"dynamic-field-2a",
"input":"number",
"validation":"required"
}
]
}
]
How will i create the dynamic input form elements and shuffle them in their respective section in accordance with the data sent from the server.
With the static i mean , these will be already present/known to us. Dynamic fields are the once that are sent by the server. Server also will sent the order in which each fields(static/dynamic) should be aligned.
Need help in this task
Hope I understood your question right.
If you want to list all fields as INPUT tag in server's response order:
<div *ngFor="let section of mySuperProvider.getDataFromServer()">
<h2>{{section.name}}</h2>
<p *ngFor="let field of section.fields">
<b>{{field.name}}</b>
<input type="text" ... >
</p>
</div>
If you want to shuffle fields, you can do it in provider or:
<p *ngFor="let field of shuffle(section.fields)">
Where shuffle() is a function:
shuffle(array) {
return array.sort(function() { return 0.5 - Math.random() });
}
If you want to show only specific types, and exclude others, then you can use *ngIf.
If you need instead of INPUT tag use Configurable Reactive Forms, then see nice article in this link, with a main idea to create dynamic component and pass config to it:
<form
class="dynamic-form"
[formGroup]="form"
(ngSubmit)="submitted.emit(form.value)">
<ng-container
*ngFor="let field of config;"
dynamicField
[config]="field"
[group]="form">
</ng-container>
</form>

select ng-options not updating ng-model in AngularJS with ajax

I have a simple question and I really dont know what am I missing in my logic.
In this Fiddle is working fine (not using ajax/timeout) but I want to understand and also fix why the following behavior is not happening when I apply the same logic with a timeout/ajax !!
Here is my simple sample: JS FIDDLE
HTML:
<body data-ng-app="appMain">
<div ng-controller="SearchController">
<input type="text" ng-model="SearchTerm" />
<input type="button" value="Submit Search" ng-click="QuerySuggestions()" />
<select ng-show="ShowSuggestion" name="cmbSelectedSuggestion" ng-model="SelectedSuggestion" ng-options="text as suggestion.Detail for suggestion in SuggestionList" ng-change="WhoIsSelected(suggestion)">
</select>
</div>
</body>
AngularJS:
angular.module('appMain',[])
.controller('SearchController',function($scope, $http, $timeout){
$scope.SearchTerm = '';
$scope.ShowSuggestion = false;
$scope.SuggestionList = [];
$scope.SelectedSuggestion = null;
$scope.QuerySuggestions = function()
{
//Simulating an AJAX that my response happens 2s afterwards
$timeout(function(){
var oJSON = {"List": [
{
"Id": 1,
"Type": "State",
"Name": "Rio de Janeiro",
"Detail": "Rio de Janeiro - State, Brazil"
}
,
{
"Id": 1,
"Type": "City",
"Name": "Rio de Janeiro",
"Detail": "Rio de Janeiro - City, Rio de Janeiro, Brazil"
}]};
$scope.SuggestionList = oJSON.List
$scope.ShowSuggestion = true;
}, 2000);
}
$scope.WhoIsSelected = function($option){
$scope.WhoIsSelectedFirstApproach();
$scope.WhoIsSelectedSecondApproach($option);
}
$scope.WhoIsSelectedFirstApproach = function(){
console.log($scope.SelectedSuggestion); //why undefined !?!?!
}
$scope.WhoIsSelectedSecondApproach = function($option){
console.log($option) //why undefined ?!?!?
}
})
In your ng-options, it should be suggestion.Detail as text instead of text as suggestion.Detail.
Well, after a bigger search I manage to solve and also understand my mistakes.
First, Due to my T-SQL background I was unterstanding that "text" was an alias for sugestion.Detail field in the expression text as suggestion.Detail for suggestion in SuggestionList but thats not the case!
The word "text" here is not an ALIAS it is the object/object.field that u want AngularJS do expose as the ng-model... so, that said, the solution in my case (object in the list as ng-model) was updating to: suggestion as suggestion.Detail for suggestion in SuggestionList
ng-options="suggestion as suggestion.Detail for suggestion in SuggestionList"
Ok that simply resolves the WhoIsSelectedFirstApproach, but if I want to pass the object to a function in the ng-change, using suggestion in the expression doenst work... (dont know why they used different expression logics for different ng-*) but to solve that problem figured that u can reference the ng-model field inside the ng-change: so I could manage that changing Function(suggestion) to Function(modelField) as follows:
ng-change="WhoIsSelected(SelectedSuggestion)"
SOLVED JS FIDDLE

Bind json data in angularjs checkbox dynamically

I would like to bind my array of json data to angularjs checkbox. I am newbiew to this technology so I couldn't figure out the exact way to solve my scenario. I have json data like below
{
"hits":{
"total":3695,
"hits":[
{
"_type":"School",
"_source":{
"message":[
"HIGH"
],
"Class":"A"
}
},
{
"_type":"School",
"_source":{
"message":[
"HIGH"
],
"Class":"B"
}
},
{
"_type":"School",
"_source":{
"message":[
"HIGH"
],
"Class":"C"
}
}
]
}
}
I have to bind the "Class" value in the angularjs checkbox.
The angularjs code which I have wrote is ,
$scope.listofschoolname = response;
<label ng-repeat="ModelName in listofschoolname ">
<input type="checkbox" ng-model="ModelName.checked" size="10" /> {{ModelName.hits.hits[0]._source.Class}}
</label>
I can get a single checkbox with value "A". Like that I would like to bind all the value in Class to checkbox.
Note: The json response which I am getting is dynamic in nature sometimes it have 10 class value(A,B,C,D,E,etc) sometimes it have only one class value(A) based on that my checkbox count and value should change.
Thanks in advance..
If I understand you correctly then you need to iterate over listofschoolname.hits.hits
$scope.listofschoolname = response;
<label ng-repeat="ModelName in listofschoolname.hits.hits ">
<input type="checkbox" ng-model="ModelName.checked" size="10"/> {{ModelName._source.Class}}
</label>

How to use function in Kendo Grid Column Template with AngularJS

I have a column in a Kendo grid that I want to perform some specific logic for when rendering, and am using Angular. I have the grid columns set up using the k-columns directive.
After looking at the documentation, it seemed simple: I could add the template option to my column, define the function to perform my logic, and pass the dataItem value in. What I have looks something like this:
k-columns='[{ field: "Name", title: "Name",
template: function (dataItem){
// Perform logic on value with dataItem.Name
// Return a string
}
}]'
However, running this causes a syntax error complaining about the character '{' that forms the opening of the block in my function.
I have seen several examples of defining a template function in this format. Is there something else that needs to be done for this to work? Am I doing something incorrectly? Is there another way of defining the template as a function and passing the column data to it? (I tried making a function on my $scope, which worked, except I couldn't figure out how to get data passed into the function.)
Thank you for your help.
It appears that defining a column template in this fashion isn't supported when using AngularJS and Kendo. This approach works for projects that do not use Angular (standard MVVM), but fails with its inclusion.
The workaround that a colleague of mine discovered is to build the template using ng-bind to specify a templating function on the $scope, all inside of a span:
template: "<span ng-bind=templateFunction(dataItem.Name)>#: data.Name# </span>"
This is the default column templating approach that is implemented by Telerik in their Kendo-Angular source code. I don't know yet if the data.Name value is required or not, but this works for us.
Warning: Don't have access to Kendo to test the code at the moment, but this should be very close
In your case, you are assigning a a string to the value of k-columns and that string contains the the word function and your curly brace {
You need to make sure the function gets executed ... something like this:
k-columns=[
{
field: "Name",
title: "Name",
template: (function (dataItem){
// Perform logic on value with dataItem.Name
// Return a string
}())
}
];
Note the difference:
We create an object -- a real honest-to-goodness object, and we use an IIFE to populate the template property.
Maybe, it will be useful for someone - this code works for me too:
columns: [
{
field: "processed",
title:"Processed",
width: "100px",
template: '<input type="checkbox" ng-model="dataItem.processed" />'
},
and you get the two-way binding with something like this:
<div class="col-md-2">
<label class="checkbox-inline">
<input type="checkbox" ng-model="vm.selectedInvoice.processed">
processed
</label>
</div>
This can be done via the columns.template parameter by supplying a callback function whose parameter is an object representing the row. If you give the row a field named name, this will be the property of the object you reference:
$("#grid").kendoGrid({
columns: [ {
field: "name",
title: "Name",
template: function(data) {
return data.name + "has my respect."
}
}],
dataSource: [ { name: "Jane Doe" }, { name: "John Doe" } ]
});
More information is available on Kendo's columns.template reference page.
After hours of searching. Here is the conclusion that worked:
access your grid data as {{dataItem.masterNoteId}} and your $scope data as simply the property name or function.
Example
template: '<i class="fa fa-edit"></i>',
I really hope this safes somebody life :)
just use like my example:
}, {
field: "TrackingNumber",
title: "#T("Admin.Orders.Shipments.TrackingNumber")",
//template: '<a class="k-link" href="#Url.Content("~/Admin/Shipment/ShipmentDetails/")#=Id#">#=kendo.htmlEncode(TrackingNumber)#</a>'
}, {
field: "ShippingMethodName",
title: "#T("Admin.Orders.Shipments.ShippingMethodName")",
template:function(dataItem) {
var template;
var ShippingMethodPluginName = dataItem.ShippingMethodPluginName;
var IsReferanceActive = dataItem.IsReferanceActive;
var ShippingMethodName = dataItem.ShippingMethodName;
var CargoReferanceNo = dataItem.CargoReferanceNo;
var ShipmentStatusId = dataItem.ShipmentStatusId;
if (ShipmentStatusId == 7) {
return "<div align='center'><label class='label-control'><b style='color:red'>Sipariş İptal Edildi<b></label></div>";
} else {
if (ShippingMethodPluginName == "Shipping.ArasCargo" || ShippingMethodPluginName == "Shipping.ArasCargoMP") {
template =
"<div align='center'><img src = '/content/images/aras-kargo-logo.png' width = '80' height = '40'/> <label class='label-control'><b>Delopi Aras Kargo Kodu<b></label>";
if (IsReferanceActive) {
template =
template +
"<label class='label-control'><b style='color:red; font-size:20px'>"+CargoReferanceNo+"<b></label></div>";
}
return template;
}

AngularJS show only filtered elements on ng-repeat

I've got a simple ng-repeat with a simple search filter.
My question is how can i show elements of this list only if filter is set ??
I want the list be empty when the search input contains no value !!
I can't get it work, all the items are displayed if search is filter.
Here the html :
<input type="search" class="form-control" placeholder="Rechercher" data-ng-model="search" />
<div data-ng-repeat="departement in departements | filter:search">
</div>
Here departements objects !
$scope.depatements = [
{"codeDept": "01", "libelleDept": "D1", "libelleRegion":"R1", "codeRegion": "04"},
{"codeDept": "02", "libelleDept": "D2", "libelleRegion":"R2", "codeRegion": "08"},
{"codeDept": "03", "libelleDept": "D3", "libelleRegion":"R3", "codeRegion":"09"}
];
Really thx to you guys.
If I understand correctly, you need a functional as in this example:
http://plnkr.co/edit/eNHrDSn0tfhJT2xJkVRC?p=preview

Categories

Resources