Add value of key that will be pushed to an array Angular - html

The value inside the input and textarea should be pushed the entire JavaScript part works, but how can I bind the ng-model so that Angular will pick up the value of entered information and push that into an array. Anyone an idea how to do that in HTML.
angular.module("forum-page", ["myApp"])
.controller("Forum", function($scope) {
$scope.comments = [
{
"name": "Kevin",
"comment": "Wat een mooi toestel vandaag ontvangen, zeer blij met mijn bestelling :)",
"country": "Nederland"
},
{
"name": "Jason",
"comment": "What a great phone I received from Meizu, will surely come back to buy again in the future",
"country": "USA"
},
{
"name": "姚宣辰",
"comment": "這個手機很標亮, 下次也會買魅族智能手機",
"country": "中国"
},
];
$scope.addComment = function() {
$scope.comments.push({ "name": $scope.name, "comment": $scope.comment, "country": $scope.country});
var dataObj = {
name: $scope.name,
comment: $scope.comment,
country: $scope.country
};
$scope.dataObj = dataObj;
res.error(function(data, status, header, config) {
alert("failure message: " + JSON.stringify({data: data}));
});
$scope.name = "";
$scope.comment = "";
$scope.country = "";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<input type="text" class="comment-box-name" ng-model="{{dataObj.name}}"/>
<input type="text" class="comment-box-comment" ng-model="{{dataObj.comment}}"/>
<textarea type="text" class="comment-box-country" ng-model="{{dataObj.country}}"></textarea>
<button ng-click="addComment()">Place comment</button>

No you cannot do that if you want that kind of automation in the template. In order to do that kind of action you need to place that action inside your click event listener which acts as the send button.
$scope.addComment = function () {
// Add validations before proceeding
theArray.push(dataObj);
}
Hope that helps

Some changes needed in your code :
1. remove {{}} from the ng-model value.
use dataObj.name,dataObj.comment,dataObj.country instead of {{dataObj.name}},{{dataObj.comment}},{{dataObj.country}}
2. use $scope object instead of var to initialize the object to perform the two way data binding.
$scope.dataObj = {
name: $scope.name,
comment: $scope.comment,
country: $scope.country
};
Demo!

Related

AngularJS $scope is undefined outside of .then function

I have a a form which includes select input but the thing is ng-options is not working
Select code
<select ng-model="selectedGender" ng-options="item.value for item in genderData">
I got the data from
ReferenceService.searchCategory("GENDER").then(function (response){
$scope.genderData = response.data;
console.log($scope.genderData);
})
This is the console.log($scope.genderData)
Array(2)
0:{referenceId: 1, category: "GENDER", key: "GENDER_KEY", value: "Male", $$hashKey: "object:3"}
1:{referenceId: 2, category: "GENDER", key: "GENDER_KEY", value: "Female", $$hashKey: "object:4"}
length:2
__proto__
:
Array(0)
but I have tried hard coding the data
$scope.genderData= [
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
];
and it worked! but I used ng-options="item.name for item in genderData">
btw don't mind the data I just searched it for fast use
EDIT:
I think I found the problem. Why is it undefined outside the function?
check this console
line 244 is undefined but line 242 is not?
store the response in var then out side the function assign that var to $scope. it is a callback issue.
If still it's showing same you can use localsorage to store and get the data. but this approach is not recomanded in angularjs. but if nothing happen then you can use this approcah also
That's because ReferenceService.searchCategory("GENDER") returns a promise.
A promise will wait until the data is resolved, and then move on to its success function callback. Which is the .then(function(response)).
So the code will get to the console.log on line 244 before the promise has finished, and $scope.genderData has been created and therefore is undefined
The console.log on line 242 will wait until the promise has been resolved, and calls the success callback function.
UPDATE:
Here an example how to correctly link the $scope to the factory.
Note that you must link to the object and not to its properties in your $scope.
Wrong:
$scope.gender = ReferenceService.data.genderData;
Correct:
$scope.gender = ReferenceService.data;
Example:
myApp.factory('ReferenceService',
function ()
{
var ReferenceService = {
// This is the global object. Link the $scope to this object
data: {
genderData: {}
},
searchCategory: function (type)
{
var getData = $http.get("URL", { params: { gender: type } }).then(
function (response)
{
// Store the data in the factory instead of the controller
// You can now link your controller to the ReferenceService.data
ReferenceService.data.genderData = response.data;
}
)
return getData;
}
}
return ReferenceService;
}
);
myApp.controller('MyController',
function ($scope, ReferenceService)
{
// Link $scope to data factory object
$scope.gender = ReferenceService.data;
// Now you only have to call the factory function
ReferenceService.searchCategory("GENDER");
// This will now log the correct data
console.log($scope.gender.genderData);
}
)

How to put form data into json file in angularjs

I am creating an application where I have to add the contacts from a form input. I want to add data from the form input field to my JSON file.
Unfortunately I am not able to find any solution for it until now. Kindly help in this regard. This is my controller code where the JSON object is also defined. I want to fetch the data from input filed to the JSON object array.
var contactManager = angular.module('contactManager', ['ngAnimate']);
// Contacts List Controller
contactManager.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/data.json').success(function(data) {
$scope.contacts = data;
//$scope.contacts = 'name';
});
}]);
// Contacts Details Controller
contactManager.controller('DetailsController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$scope.contact = [{
"name": "Stephen Radford",
"phone": "0123456789",
"address": "123, Some Street\nLeicester\nGH1 2SR",
"email": "stephen#email.com",
"website": "stephenradford.me",
"notes": ""
},
{
"name": "Alan Border",
"phone": "154648445",
"address": "457, Some Street\nBirmingham\nLM1 2AB",
"email": "stephen#email.com",
"website": "alanborder.me",
"notes": ""
},
{
"name": "Misbah ul Haq",
"phone": "8899556744",
"address": "458, Some Street\nFaisalabad\nFD1 2MH",
"email": "misbah#email.com",
"website": "misbah.me",
"notes": ""
}
];
$scope.contactId = $routeParams.contactId;
$scope.addNew = function() {
$scope.contact.push($scope.newData);
$scop.newData = null;
$scope.added = true;
};
}
]);
This is my form code. Where I am taking the input from a form
<form class="form-horizontal" ng-submit="addNew()" ng-controller="DetailsController">
<input ng-model="contact.name">
<input ng-model="contact.phone">
<input ng-model="contact.address">
<button>Click here to store data</button>
</form>
You need to send the object to data storedata function.
<button ng-click="storedata(obj)">Click here to store data</button>
Than, you can do it whatever you want.
$scope.storedata = function(obj) {
// obj is json
$post('/path_to_server', obj);
};

AngularJS getting in trouble with my JSON

I have got a JSON object from my website:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”},
}
and AngularJS to manage the dynamic content but it doesn't seem to be working:
var app = angular.module('myApp', []);
function PeopleCtrl($scope, $http) {
$scope.people = [];
$scope.loadPeople = function () {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function (data, status) {
$scope.people = data;
});
};
}
Here is a JSFiddle.
Can anybody help me with displaying data?
#qqruza to get the callback working properly in your jsfiddle.net/1zuteco7, change the url to this:
http://test.eventident.com/api/last_posts/siteid=&callpage=1&perpage=10&callback=JSON_CALLBACK
Notice the JSON_CALLBACK in the end. The rest of your app will still not work though cause you are not picking the right bindings from the returned data in your repeat directive. Try console.log(data) in the success function to click through the returned object and get to the right paths.
There were a number of issues with your JSON, I have resolved them.
It had different types of quotes in there. I have replaced them with ".
It now looks like this:
[{         
"ID": "100",
"role": {            
"subscriber": true         
},
"first_name": "Test",
"last_name": "Test2",
"custom_fields": {            
"job_title": "subscriber"         
},
}, {   
"ID": "102",
"role": {            
"subscriber": true         
},
"first_name": "Test 3",
"last_name": "Test 4",
"custom_fields": {            
"job_title": "testing"         
},       
}]
Also, you were not referencing the model fields correctly in your view.
Here is the updated working fiddle: http://jsfiddle.net/kmmmv83y/1/
You had a comma at the end of the last property, that will typically error everything out, the below JSON should work:
{ "ID":"102”,
"role":{“subscriber”:true},
"first_name”:”Test 3”,
"last_name”:”Test 4”,
"custom_fields":{ “job_title”:”testing”}
}

How to submit nested json when using a dynamic ng-model in angular

I have a working angular form with a dynamic model.
<input type="text" ng-model="formData[component.model]">
component.model is retrieved from a json structure that looks like this:
{
"components": [
{
"model": "address.street"
},
{
"model": "address.postcode"
},
{
"model": "adress.city"
}
]
}
This works fine, except the resulting json that is submitted by the form is flat and looks like this:
{
"name": "John",
"address.street": "kingsway road",
"address.postcode": "SE16EH",
"address.city": "London"
}
And I need more complex json like:
{
"name": "John",
"address": {
"street": "kingsway road",
"postcode": "SE16EH",
"city": "London"
}
}
Everything works fine when I hardcode the ng-model to for example:
ng-model="formData.address.street"
But with the dynamic stuff the resulting json is flat.
Does anyone know how I can get this to work?
I was facing the same problem as you and I finally found a solution: https://stackoverflow.com/a/32096328/7126683
So you just have to create a new directive like that one:
this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {
return {
restrict: 'A',
terminal: true,
priority: 100000,
link: function (scope, elem) {
var name = $parse(elem.attr('dynamic-model'))(scope);
elem.removeAttr('dynamic-model');
elem.attr('ng-model', name);
$compile(elem)(scope);
}
};
And in your template, replace the ng-model with the dynamic one.
<input dynamic-model="'formData.' + component.model" type="text">

Chained State city dropdown list from JSON

I am trying to populate a chained State City select dropdowns. I am using an external json file to do so, which consists of State and their corresponding city name, id and pincode. Can somebody gimme some idea on how to achieve this. I need to populate the city and pincode value based on the state selection. Thanks in advance...
JSON
{
"Alaska" : [
{"id": "1", "name": "Adak", "pincode": "xxx1"},
{"id": "2", "name": "Akhiok", "pincode": "xxx2" },
{"id": "3", "name": "Akiak", "pincode": "xxx3" },
],
"Arizona" : [
{"id": "4", "name": "Apache Junction", "pincode": "xxx4"},
{"id": "5", "name": "Avondale", "pincode": "xxx5"},
{"id": "6", "name": "Benson", "pincode": "xxx6"},
],
"Alabama" : [
{"id" : "5", "name": "Abbeville", "pincode": "xxx7" },
{"id" : "7", "name": "Adamsville", "pincode": "xxx8" },
{"id" : "8", "name": "Akron", "pincode": "xxx9" },
]
}
Final rendered html
<select id="state">
<option value="1">Alaska</option>
<option value="2">Arizona</option>
<option value="3">Alabama</option>
</select>
<select id="city">
<option value="4">Adak</option>
<option value="5">Akhiok</option>
<option value="6">Akiak</option>
</select>
<input id="pincode" type="text" />
I find your question interesting and wrote the corresponding solution which you can see live here.
Here is the code:
jQuery(document).ready(function () {
var myData;
var onCityChange = function (e) {
var cityData = $("option:selected", e.target).data('pincode');
$("#pincode").val(cityData.pincode);
};
var onStateChange = function (e) {
var state = $("option:selected", e.target).text();
if (state && myData) {
var stateData = myData[state];
if (stateData && stateData.length > 0) {
$("#city").empty();
$("#city").unbind('change');
for (var i = 0; i < stateData.length; i++) {
var cityData = stateData[i];
var option = $('<option value="' + cityData.id + '">' + cityData.name + '</option>')
.data('pincode', cityData);
$("#city").append(option);
}
$("#city").bind('change', onCityChange)
.trigger('change');
}
}
};
$.ajax({
url: 'DependendSelectsFromJson.json',
dataType: 'json',
success: function (data) {
var stateOptions = "", stateId = 1;
for (var prop in data) {
if (data.hasOwnProperty(prop)) {
stateOptions += '<option value="' + stateId + '">' + prop + '</option>';
stateId++;
}
}
myData = data;
$("#state").html(stateOptions)
.bind('change', onStateChange)
.trigger('change');
}
});
});
to get access about the pincode of the second (city) select box I used jQuery.data function which I find very practical if one need to associate some additional information with an DOM element. One could save only pincode value in the way, but I used the function to save full information about the city.
UPDATED: I forgot to mention that the JSON data which you posted has errors. You should remove commas before ']'. Probably it is just a problem with cut&paste of the data to the text of the question.
there are many ways.
global Varible option.
var json_object = {
"Alaska" : {}
}; //and the rest of other text too lazy to type :)
$('#state').change(function(){
var state = $(this).val();
cities = json_object[state];
$('#city').html('');//remove the prev elements
for(item in cities){//same as foreach in php
$('<option value=""></option>').appendTo($('#city'));
}
});
i must admit is not complete but giving you the rough idea.
Other wise use ajax like so
$('#state').change(function(){
var url = 'ajax.php';//should return json with a list of cities only
var state = $('#state').val();
var data = {'state':state};
$.ajax({
url:url,
data:data,
dataType:'json',
success: function(items){
//do something with it
}
})
});
The only thing you need to know is that both have their advantages and disadvantages.
first option : can only fire one request but loads sh*t loads of data that are not needed.
second option: makes more request but less data