I'm working on one angularjs form which includes location text field. For location text field I'm using google maps to autocomplete. Problem is, I'm unable to store full data database using data-ng-model. Because, only entered text is getting binded and stored in database, not full data. For Example, If I type "Pun" autocomplete populates "Pune, Maharashtra, India", but only "Pun" is storing in database(because I only typed "Pun" in text field. How to capture full data and convert it into json and store it in database? Please help me with this. Thanks in advance.
Here is my code:
JavaScript
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController',[ '$scope', '$http', function($scope, $http) {
/* $scope.myDataBlurred = $scope.area; */
$scope.list = [];
$scope.headerText = 'AngularJS Post Form Spring MVC example: Submit below form';
$scope.blurred = function() {
$scope.myDataBlurred = $scope.area;
}
$scope.submit = function() {
var formData = {
"agreement_exp_date" : $scope.agreement_exp_date,
"amenities" : $scope.amenities,
"area": $scope.myDataBlurred,
"bathrooms" : $scope.bathrooms,
"bedrooms" : $scope.bedrooms,
"State": $scope.State,
"city": $scope.city,
"country" : $scope.country,
"current_property_status" :$scope.current_property_status,
"car_spaces" : $scope.car_spaces,
"expired" : $scope.expired,
"furnished" : $scope.furnished,
"floor_or_level" : $scope.floor_or_level,
"house_number" : $scope.house_number,
"notes" : $scope.notes,
"ofname" : $scope.ofname,
"pfname" : $scope.pfname,
"parking_type" : $scope.parking_type,
"pincode" : $scope.pincode,
"prop_avail_date" : $scope.prop_avail_date,
"prpty_owner_email_id" : $scope.prpty_owner_email_id,
"prpty_pm_email_id" : $scope.prpty_pm_email_id,
"prpty_registration_no" : $scope.prpty_registration_no,
"prpty_type" : $scope.prpty_type,
"sqft" : $scope.sqft,
"street_name" : $scope.sqft,
"verified" : $scope.verified,
"prpty_type_sub" : $scope.prpty_type_sub,
"published_on": $scope.published_on,
"profile": $scope.profile
/* "location" : $scope.location,
"phone" : $scope.phone */
};
var response = $http.post('/Owner/addprop', formData);
response.success(function(data, status, headers, config) {
$scope.list.push(data);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
//Empty list data after process
$scope.list = [];
$scope.$setPristine();
};
}]);
</script>
HTML
<div class="col-md-6">
<span> Location<i style="color: red;">*</i>
<div id="locationField">
<input id="autocomplete" name="property_loc"
placeholder="Search for location" onFocus="geolocate()"
type="text" class="form-control" value="${locn}" data-ng-model="area" ng-blur="blurred()" required></input>
</div>
</div>
Go for this code!
It works with the Google Maps API. Start by typing a city name in the input field!
Dont`t look at the warnings and errors. If you add an API key it works without!
var myApp = angular.module('myApp', []);
myApp.directive('googleplace', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, model) {
var options = {
types: []
};
scope.gPlace = new google.maps.places.Autocomplete(element[0], options);
google.maps.event.addListener(scope.gPlace, 'place_changed', function() {
scope.$apply(function() {
model.$setViewValue(element.val());
});
});
}
};
});
function MyCtrl($scope) {
$scope.gPlace;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div>Your location is: {{chosenPlace}}</div>
<div><input ng-model="chosenPlace" googleplace/></div>
</div>
Related
Using a factory, I want to get information from one page (text fields and a submit button), put it in an array, and read from that array to post it into a different page. Here is a snippet of my code.
app.factory("service", function(){
var serv = {};
serv.arr = [];
serv.add = (title, name, post, tag) => serv.arr.push({
"title" : title, "name" : name, "post" : post, "tag" : tag
});
return serv;
});
app.controller("createCtrl", ["$scope", "service", function($scope, service)
{
display = () => service.add($scope.title, $scope.name, $scope.post,
$scope.tag);
console.log(service.arr);
}]);
app.controller("newsCtrl", ["$scope", "service", function($scope, service){
$scope.newsPage = "News";
$scope.array = service.arr;
}]);
I know I'm probably way off but at this stage I can't even tell if any information is being added to the array.
Try below code for set & get data from factory.
Click on SAVE DATA & then GET DATA buttons to see the actions
(function(ng, app){
app = angular.module('app', [])
app.factory("service", function(){
var serv = {};
var arr = [];
return {
add : function (title, name, post, tag) {
arr.push({
"title" : title, "name" : name, "post" : post, "tag" : tag
});
},
get : function (firstname) {
return arr[0];
}
}
});
app.controller("createCtrl", ["$scope", "service", function($scope, service)
{
$scope.display = function(){
service.add($scope.title, $scope.name, $scope.post, $scope.tag);
};
}]);
app.controller("newsCtrl", ["$scope", "service", function($scope, service){
$scope.newsPage = "News";
$scope.getData = function(){
$scope.array = service.get();
};
}]);
}(angular));
input {
margin: 5px;
}
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="createCtrl as main">
<h1>create Ctrl</h1>
<input ng-model="title" placeholder="title" /><br/>
<input ng-model="name" placeholder="name" /><br/>
<input ng-model="post" placeholder="post" /><br/>
<input ng-model="tag" placeholder="tag" /><br/>
<button ng-click="display()"> SAVE DATA </button>
</div>
<br/> <hr/>
<div ng-controller="newsCtrl">
<h2>news Ctrl </h2>
<button ng-click="getData()"> GET DATA </button>
<p> title : {{array.title}} </p>
<p> name : {{array.name}} </p>
<p> post : {{array.post}} </p>
<p> tag : {{array.tag}} </p>
</div>
</body>
</html>
Here is My html page which is a basic form that has the list of details for scheduling a test
<div class="container panel">
<form ng-submit="submit(testConfigForm)">
<input type="text" name="testName" ng-model="test.testName"> Test Name <br/>
<input type="date" name="testDate" ng-model="testConfigForm.testDate"> Test Date <br/>
<input type="number" min="0" max="100" name="testTargetScore" ng-model="testConfigForm.testScore"> Test Score <br/>
<span ng-repeat="unit in units">
<label><input type="checkbox" name="checkbox" ng-model="testForm.chapters[$index]">{{unit.name}}</label><br>
</span>
<input type="submit" value="Save">
</form>
This is how my controllerlooks like
app.controller('TestConfigurationCtrl', ['$scope', '$routeParams', '$sce', '$http', 'chapterService',
function ($scope, $routeParams, $sce, $http, unitService) {
$scope.chapters = unitService.getUnits();
$scope.postUrl = $sce.trustAsResourceUrl($routeParams.content_item_return_url);
$scope.submit = function(testConfigForm) {
var config = {
"#context" : [],
"#graph" : [ {
"#type" : "ContentItemPlacement",
"placementOf" : {
"#type" : "LtiLink",
"text" : "test",
"mediaType" : "application/vnd.ims.lti.v1.launch+json",
"title" : "Test Exam",
"custom" : {
"name" : testConfigForm.testName,
"dueDate" : testConfigForm.testDate,
"targetScore" : testConfigForm.testTargetScore,
"chapters" : testConfigForm.units
},
"activityType" : "abc",
"activityId" : "1"
}
} ]
};
$http.post($scope.postUrl, config)
.success(function (data, status, headers, config)
{
$scope[resultVarName] = data;
})
.error(function (data, status, headers, config)
{
$scope[resultVarName] = "SUBMIT ERROR";
});
};
}]);
});
How can i post the data from the form. It gives me an error of failed to load resource
I think I found the problem, is this:
$scope.postUrl = $sce.trustAsResourceUrl($routeParams.content_item_return_url);
...
$http.post($scope.postUrl, config)
You shouldn't use $scope.postUrl on post, use the url as is:
var postUrl = $routeParams.content_item_return_url;
$scope.postUrl = $sce.trustAsResourceUrl(postUrl);
...
$http.post(postUrl, config)
In order to make use of Angular JS I tried to use Factory for my data stack...
Now, It does not work. I have just put a simple json data to be returned by factory, and then
the script has stopped working. It is the most basic example of angularjs as it uses json to
repeat and iterate through.
Here is all angularjs that I have written:
var Item = angular.module("Item", ['ngRoute']);
Item.config(function($routeProvider){
$routeProvider
.when("/add", {
controller : "ItemController",
templateUrl : "index.html"
})
.when("/edit", {
controller : "ItemController",
templateUrl : "index.html"
});
});
Item.factory("ItemsFactory", function(){
var items = [
{ name : "Washing Powder",
price : "2000",
balance : 14
},
{ name : "Shampoo",
price : "8500",
balance : 03
},
{ name : "Soap",
price : "1850",
balance : 27
}
];
var factory = {};
factory.getItems() = function(){
return items;
};
factory.postItems() = function(){
// POST items
};
return factory;
});
Item.controller("ItemController", function($scope, ItemsFactory){
$scope.items = ItemsFactory.getItems();
init();
function init()
{
$scope.items = ItemsFactory.getItems();
}
$scope.AddNewItem = function(){
$scope.items.push({
name : $scope.NewItem.name,
price : $scope.NewItem.price
});
};
});
And here is the HTML markup:
<!DOCTYPE html>
<html >
<head>
<title>Practicing AngularJS Framework...!</title>
<script src="angular.js" type="text/javascript"></script>
<script src="ngroute.js" type="text/javascript"></script>
<script src="scripts.js" type="text/javascript"></script>
</head>
<body data-ng-app="Item">
<div data-ng-controller="ItemController">
<div data-ng-repeat="each in items">
<p>Item {{ each.name }} costs {{ each.price }}.</p>
</div>
<div>
<input type="text" data-ng-model="NewItem.name" />
<input type="text" data-ng-model="NewItem.price" />
<br />
<input type="submit" value="Add Item" data-ng-click="AddNewItem()" />
</div>
</div>
</body>
</html>
It does not load of the json content to repeat them instantly...Nothing happens..
I think it is better to use some thing like this to return value in service :
Item.factory("ItemsFactory", function(){
var items = [
{ name : "Washing Powder",
price : "2000",
balance : 14
},
{ name : "Shampoo",
price : "8500",
balance : 03
},
{ name : "Soap",
price : "1850",
balance : 27
}
];
return {
getItems: function(){
return items;
},
postItems:function(){
}
});
also it think :
factory.getItems() = function(){}
is wrong and the correct is :
factory.getItems = function(){}
Overview
I am building an app (running on MAMP) that holds contact information that will expand to hold more data such as project name & deadline, once this part is functional.
Questions
When the user visits /projects.php#/project/ I would like them to see a list of all the project names with a link to their detail page.
How should I write the following to access all of my data?
Do I need the .json at the end?
What does the #id do?
return $resource('data/project.json/:id', {id: '#id'});
When the user visits /projects.php#/project/a-gran-goodn I would like them to see the details about this project(for now, just the name & address).
How should I write the following to return my data by Id?
$scope.project = $routeParams.id ? Project.get({id: $routeParams.id}): new Project();
plunkr file
http://plnkr.co/edit/7YPBog
project.json
This file lives on http://localhost:8888/angularjs/ProjectsManager/data/project.json
[
{ "address" : [ " 3156 Dusty Highway",
" Teaneck New Jersey 07009-6370 US"
],
"id" : "a-gran-goodn",
"name" : "Grania Goodner",
"phone" : " (862) 531-9163"
},
{ "address" : [ " 62 Red Fawn Moor",
" Rodney Village West Virginia 25911-8091 US"
],
"id" : "b-aime-defranc",
"name" : "Aimery Defranco",
"phone" : " (681) 324-9946"
}
]
app.js
var projectsApp = angular.module('projects', ['ngResource']);
projectsApp.config(function($routeProvider) {
$routeProvider
.when('/', {
controller: 'ProjectListCtrl',
templateUrl: 'partials/projectlist.html'})
.when('project/:id', {
controller: 'ProjectDetailCtrl',
templateUrl: 'partials/projectdetail.html'
})
.otherwise('/');
});
projectsApp.factory('Project', function($resource) {
return $resource('data/project.json/:id', {id: '#id'});
});
projectsApp.controller('ProjectListCtrl', function(Project, $scope) {
$scope.projects = Project.query();
console.log($scope.projects);
});
projectsApp.controller('ProjectDetailCtrl', function(Project, $routeParams, $scope) {
$scope.project = $routeParams.id
? Project.get({id: $routeParams.id})
: new Project();
});
partials/projectlist.html
Add new item
<ul class="unstyled">
<li ng-repeat="project in projects">
<div class="well">
<h2><small>{{project.id}}</small> {{project.name}}</h2>
View Info for {{project.name}}
</div>
</li>
</ul>
partials/projectdetails.html
<h3>Information</h3>
<p>Name: {{project.name}}</p>
<p>Phone Number: {{project.phone}}</p>
<p ng-repeat="line in project.address">{{line}}</p>
index.php
<?php
header('Access-Control-Allow-Origin: *');
?>
<!doctype html>
<html ng-app="projects">
<head>
<meta charset="utf-8">
<title ng-bind="title" ng-cloak>Restaurant —</title>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
</head>
<body ng-controller="ProjectListCtrl">
<a class="brand" href="#">Projects Manager</a>
<div id="app-container" class="container-fluid">
<div class="row-fluid">
<div class="span12" id="main" ng-view>
</div><!--/.span12-->
</div><!--/.row-fluid-->
<footer>Copyright Projects © 2013</footer>
</div><!--/.container-->
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<!-- Don't forget to load angularjs AND angular-resource.js -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular-resource.js></script>
<!--Controllers-->
<script src="app.js"></script>
</body>
</html>
Since you can't query against a raw JSON file like you can with RESTful-style URLs (which is what $resource is built to do), you can instead get a copy of the JSON and then build your own query, get, etc. that looks at the data and returns the right thing. It's a bit tricky because you also want to support new Project, which doesn't really make sense when using a file-backed store, but this example supports it:
projectsApp.factory('Project', function($http) {
// Create an internal promise that resolves to the data inside project.json;
// we'll use this promise in our own API to get the data we need.
var json = $http.get('project.json').then(function(response) {
return response.data;
});
// A basic JavaScript constructor to create new projects;
// passed in data gets copied directly to the object.
// (This is not the best design, but works for this demo.)
var Project = function(data) {
if (data) angular.copy(data, this);
};
// The query function returns an promise that resolves to
// an array of Projects, one for each in the JSON.
Project.query = function() {
return json.then(function(data) {
return data.map(function(project) {
return new Project(project);
});
})
};
// The get function returns a promise that resolves to a
// specific project, found by ID. We find it by looping
// over all of them and checking to see if the IDs match.
Project.get = function(id) {
return json.then(function(data) {
var result = null;
angular.forEach(data, function(project) {
if (project.id == id) result = new Project(project);
});
return result;
})
};
// Finally, the factory itself returns the entire
// Project constructor (which has `query` and `get` attached).
return Project;
});
You can use the results of query and get like any other promise:
projectsApp.controller('ProjectListCtrl', function(Project, $scope) {
$scope.projects = Project.query();
});
projectsApp.controller('ProjectDetailCtrl', function(Project, $routeParams, $scope) {
$scope.project = $routeParams.id
? Project.get($routeParams.id)
: new Project();
});
Note the change to Project.get($routeParams.id); also, the updated Plunker also fixes a problem in your $routeProvider configuration.
This is all demonstrated here: http://plnkr.co/edit/mzQhGg?p=preview
i will paste here a generic code i use to fetch json from your local or a remoteserver maybe it will help you:
it uses a factory that you can call when you need it.
app.factory('jsonFactory', function($http) {
var jsonFactory= {
fromServer: function() {
var url = 'http://example.com/json.json';
var promise = $http.jsonp(url).then(function (response) {
return response.data;
});
return promise;
},
hospitals: function() {
var url = 'jsons/hospitals.js';
var promise = $http.get(url).then(function (response) {
return response.data;
});
return promise;
}
};
return jsonFactory;
});
Then when you need to call it:
function cardinalCtrl(jsonFactory, $scope, $filter, $routeParams) {
jsonFactory.hospitals().then(function(d){
$scope.hospitals=d.hospitals;
});
jsonFactory.fromServer().then(function(d){
$scope.fromServer=d.hospitals;
});
}
I am building an app with Angular.js accesing the LinkedIn API. What happens is that when I do a call to the API, the model does not get refreshed inmediately, but after I do another change on the screen. For example, I have binded the API call to a button, but I have to press it twice for the screen to get the data refreshed. This is my controller:
angbootApp.controller('AppCtrl', function AppCtrl($scope, $http) {
$scope.getCommitData = function() {
IN.API.Profile("me").fields(
[ "id", "firstName", "lastName", "pictureUrl",
"publicProfileUrl" ]).result(function(result) {
//set the model
$scope.jsondata = result.values[0];
}).error(function(err) {
$scope.error = err;
});
};
});
And this is my button and a link with the content:
<div>
{{jsondata.firstName}}
<form ng-submit="getCommitData()">
<input type="submit" value="Get Data">
</form>
</div>
EDIT: Explanation on how I did it here
You need to call $scope.$apply when retrieving the results/error
angbootApp.controller('AppCtrl', function AppCtrl($scope, $http) {
$scope.getCommitData = function() {
IN.API.Profile("me").fields(
[ "id", "firstName", "lastName", "pictureUrl",
"publicProfileUrl" ]).result(function(result) {
//set the model
$scope.$apply(function() {
$scope.jsondata = result.values[0];
});
}).error(function(err) {
$scope.$apply(function() {
$scope.error = err;
});
});
};
});
Anything outside angular world does not trigger automatic refresh of the views.
See $apply