check values in ng-repeat and $http post it AngularJs [duplicate] - angularjs

This question already has an answer here:
Add boolean checkboxes ng-model to object AngularJS
(1 answer)
Closed 4 years ago.
I am trying to add a checkboxes in ng-repeat, and then post with $http checked values.
Here is my code :
$scope.add_to_post = function(n){
console.log("name",n);
$http({
method: 'POST',
url: url,
data: $.param({
name: n,
}),
withCredentials: true,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
.then(function successCallback(data) {
console.log('post');
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
};
HTML:
<div >
<ul ng-repeat="x in messages" style="list-style:none;">
<li>
{{x.name}}
<input type="checkbox" ng-click="add_to_post(x.name)"/>
</li>
</ul>
<button ng-click="post()">post</button>
I want option that I check some checkboxes, then I click post and $http calls are running.
My plunker : http://next.plnkr.co/edit/zPu9DH0JyinlBvLh
Thanks for answers and help in advance!

In your controller you can create an object for storing the models (ng-model) for your checkboxes like this:
$scope.modelCheck = {};
then in the html you can bind them like this:
<input type="checkbox" ng-model="modelCheck[x.name]"/>
finally, when you are going to do the POST collect the check boxes name which where marked as true like this:
$scope.post = function(){
var data = [];
for (var k in $scope.modelCheck) {
// `k` is own property (checkbox name) and its value is `true`
if ($scope.modelCheck.hasOwnProperty(k) && $scope.modelCheck[k]) {
data.push({'name': k});
}
}
console.log(data);
// do with data as you wish from here
};
See this Forked working plunker (see the console)

Related

angular - ui grid shows data only if I type in something on the filter field, but data gets bind to the grid though

Here's is my GRID div code - the div gets visible if data is returned
<div ng-if="showDiv" class="col-sm-12 ocdspacing">
<div class="col-sm-12 text-right">
<span><button class="btn btn-success" ng-click="ShowReasonDialog()">Reason Code</button></span>
<div ui-grid="gridMEE" class="table text-center" ui-grid-grouping ui-grid-selection ui-grid-auto-resize></div>
</div></div>
Here's is my binding function -
$scope.GetCustomerData = function (custno) {
$.ajax({
url: 'MenuExpansionOpportunityExclusions.aspx/GetCustomerData',
type: 'POST',
dataType: 'json',
data: "{" + "strCustomerCD" + ": '" + custno + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
$scope.gridMEE.data = JSON.parse(data.d);
console.log(data);
if (data.d == null) {
$scope.showDiv = false;
}
else {
$scope.showDiv = true;
}
},
error: function (response) {
$scope.showDiv = false;
}
});
};
The issue is that..the grid binds the data.. but shows only if any type event is fired, suppose I type something in a text box..then only it shows the data..please help.
I got the solution. As I am using $.ajax function, I should use $scope.$apply() to let angular to update the scope.
Try to change ng-if to ng-show.
It is possible that ng-if creates a new scope and your data does not propagate correctly.
EDIT:
I cannot add a comment, because of low reputation, but this is follow-up to your found solution.
You should use $html or $q/$resource services to send requests.
Since, You are building angular app, it's recommended to use angular services.
$html service would serve you well in this example, and possibly will save some time and bugs in the future.

How to do global search in Angularjs from json array?

Iam able to display and filter search results in the same view..But how can i create search box in header navbar which is common to all pages. On click of search button should open the separate page and should load the search results alphabetically from json array based on the value entered in search box. How to do this? Kindly help
This is one way of attacking your problem. If i understood your problem correctly you wanted to filter out a JSON array...
So lets say in mainCtrl we have this:
$http({
method: 'GET',
url: '/Users'
}).then(function successCallback(response) {
$scope.usersJson = response;
}, function errorCallback(response) {
console.error("Something Happened...");
});
So lets say that data above gives us a sample of Users that look like this:
"Username" : {
"name" : "Username",
"value" : "Hello World"
}
Then in our html if we want to go through the data:
<body ng-app="app" ng-controller="mainCtrl">
<input type="text" ng-model="search" />
<p ng-repeat="message in messages | filter: search">
Name: {{ message.name }}
Message : {{message.value}}
</p>
</body>
You have to learn more about the ngFilter Directive and Filtering in AngularJS In general.. Here is the docs about it.. Hope this helped!
EDIT
If you want to do this in multiple controllers, just make a service to serve as a communication beetween controllers...
app.service("jsonArray", function($scope){
this.getArray = function(){
$http({
method: 'GET',
url: '/Users'
}).then(function successCallback(response) {
return response;
}, function errorCallback(response) {
console.error("Something Happened...");
});
}
})
Now you can inject this service to a controller and simply do jsonArray.get() to get the JSON List..
How to inject service into controller?
Sample:
app.controller('mainCtrl', ["$scope", "jsonArray", function($scope, jsonArray){
}])
Hope this helped..

Want to get the array of form element's value in AngularJS

HTML Form code
<form ng-submit="mysubmit()" ng-controller="question_post" >
<textarea name="question" id="question" ng-model="question"></texarea>
<input type="text" name="opt[]" ng-model="opt[]" />
<input type="text" name="opt[]" ng-model="opt[]" />
</form>
Angular JS Code
var obj = angular.module('root', []);
obj.controller('question_post', ['$scope','$http', function ($scope,$http) {
$scope.mysubmit = function(){
$http({
url: "some_url",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data:$.param({user_id:1,'question':$scope.question,'option':$scope.opt})
}).success(function(data, status, headers, config) {
console.log(data);
alert(data);
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}
}]);
The code above returns error when I write ng-model="opt[]", and ng-model="opt" returns a value.
I'm trying to add the dynamic text fields with name opt, and for this I want to get the opt value in an array.
If I'm using PHP then its okay ($option =$_POST['opt']) but how can I get the array value of opt in AngularJS.
You could define the options within your controller, pass it along to the view and use ng-repeat to iterate over your options. This way you could use $index and save your options into an array. Here is a Plunker as an example.
So basically you iterate over your options, as mentioned:
<div ng-repeat="option in vm.options">
<input type="text" name="{{ option.name }}" ng-model="vm.opt[$index]" />
As you can see I used ng-model like this:
ng-model="vm.opt[$index]"
This will save the value of the input field in an array at the position of $index, which is much like the iterator in a for-loop and starts with 0.

ngResource GET with filter values

I'm writing a small test application where I can retrieve my customers from a parse.com database.
I have the following form in html
...
<body ng-app="myApp">
<div ng-controller="CustomerController">
<button ng-click="getCustomers()">Get customers</button>
<ul>
<li ng-repeat="customer in customers">{{ customer.name }}</li>
</ul>
</div>
</body>
...
My angular app is the following:
Module
var app = angular
.module('myApp', ['ngResource'])
.constant('myConfig', {
'api_url': 'https://api.parse.com/1/classes/',
'parse_application_id': 'xxxxxxxxxxxxx',
'parse_rest_api_key': 'xxxxxxxxxxxxx'
});
Factory
app.factory('CustomersService', function($resource, myConfig) {
return $resource(myConfig.api_url + 'Customer', {}, {
query: {
method: 'GET',
isArray: false,
headers: {
'X-Parse-Application-Id': myConfig.parse_application_id,
'X-Parse-REST-API-Key': myConfig.parse_rest_api_key
}
},
create: {
method: 'POST',
headers: {
'X-Parse-Application-Id': myConfig.parse_application_id,
'X-Parse-REST-API-Key': myConfig.parse_rest_api_key
}
}
})
});
Controller:
app.controller('CustomerController', function($scope, CustomersService, CustomerService) {
$scope.getCustomers = function() {
CustomersService.query().$promise.then(function(result) {
$scope.customers = result.results;
});
};
});
So when I click my button, everything works like it should.
But I also want to add a filter by name when I want to retrieve customers from the database.
When I execute the following in Postman
https://api.parse.com/1/classes/Customer?where={"name":"aaaaa"}
this works and only gets the customer with the name "aaaaa". So I know that the syntax is OK.
So I will add a textbox where the user can enter a customername and after that I want to click on the search button.
But how can I manage the ?where={"name":"aaaaa"} into the angular stuff when I click the button? I also want to expand the filter with other columns from that customer.
Something like this should work (assuming everything goes in the where object)
Add some search fields that bind to a scoped object's properties. We'll call it search
<label for="search_name">Name</label>
<input type="text" ng-model="search.name" name="name" id="search_name">
<label for="search_city">City</label>
<input type="text" ng-model="search.city" name="city" id="search_city">
Then you can execute the query action with
CustomersService.query({where: $scope.search}).$promise...
That should create a query param like
?where=%7B%22name%22%3A%22aaaaa%22%2C%22city%22%3A%22London%22%7D
which is the URI encoded value
?where={"name":"aaaaa","city":"London"}

Typehead displays wrong on certain input

I am using a uiTypehead for input selection.
It works well except for a simple fact. My inputs always have the form like
{name: "Las Vegas McCarran International (LAS)<span
class="country">United States</span>", iata: "LAS"}
So I insert <span class="country">...</span> from my backend into the string.
When I then type in "veg" into the input field, that's all fine.
However, when typing in "las" instead, following happens:
What basically happens is, that my system assumes "class" to be part of my desired string does the following in the view:
<span c<strong="">lass="country">United States</span>
Basically, it recognizes "las" as the string and puts a strong into that part so that it is not displayed correctly.
My view, service and my controller look as follows:
Service:
angular.module('tripdeltaApp').service('airportService',['$http',function($http){
this.airport = function (entry) {
return $http({
method: 'POST',
url: '/airport',
data: {'search': entry}
}).then(function (response) {
return response.data.map(function (item) {
//console.log(item);
return item;
});
});
};
}]);
Controller:
$scope.onSelect = function ($item, $model, $label,to,index) {
$model = urlParser.cleanAirport($model);
if(to && $scope.flightArray[index+1] && !$scope.flightArray[index+1].from) {
$scope.flightArray[index+1].from = $model;
}
};
and view:
<input type="text"
ng-focus="inputFocus=false"
ng-blur="inputFocus=true"
ng-model="flight.to"
placeholder="{{'TO'|translate}}"
name="arrivalAirport"
typeahead="data as data.name for data in getAirport($viewValue)"
class="form-control"
typeahead-editable="false"
typeahead-on-select="onSelect($item, $model, $label,1,$index)"
autocomplete="off"
select-on-click
required>
Any idea how to solve that?
I think your best bet is to use a Custom Template, as described in the Typeahead example with the flags, instead of putting markup into your data.
You'd change your data to be like this:
{name: "Las Vegas McCarran International (LAS)", country: "United States", iata: "LAS"}
and use a template something like this:
<script type="text/ng-template" id="customTemplate.html">
<div>
{{match.model.name}}
<span class="country">{{match.model.country}}</span>
</div>
</script>
Update
If you can't change the data on the backend, you could preprocess your data as it gets loaded into JavaScript:
var re = new RegExp('^([^<]+)<span class="country">([^<]+)<\/span>');
angular.module('tripdeltaApp').service('airportService',['$http',function($http){
this.airport = function (entry) {
return $http({
method: 'POST',
url: '/airport',
data: {'search': entry}
}).then(function (response) {
return response.data.map(function (item) {
//console.log(item);
var matches = item.name.match(re);
item.name = matches[1];
item.country = matches[2];
return item;
});
});
};
}]);
The regular expression may need some tweaking, based on the specific data you have. If any airport "name" fields have a "<", that would obviously cause trouble. You may also need to mess with spacing, location of quotes, etc.

Resources