Angular - Get data into ng-Model from object in controller - angularjs

I am not able to put the data into ng-model in view from an object in controller.
VIEW1 :
<input type="text" class="user-input" name="profile.firstname" ng-model="profile.firstname" ng-minlength="2" required pattern=".{2,}" placeholder="E.g. Anvika" title="Please enter atleast 2 characters">
When I click a button in VIEW2, it fires a function (say function 'test').
VIEW2
<input type="submit" ng-click="register.test()" ui-sref="doctorRegister" value="Profile">
CONTROLLER:
var app = angular.module('app');
app.controller('registerController', ['$scope', 'tempDataStorageService', function ($scope, tempDataStorageService) {
var register = this;
register.doctor = {};
register.test = function () {
register.refreshProfile = tempDataStorageService.get(register.doctor.profile);
//console.log(register.refreshProfile);
var a = register.refreshProfile.firstname;
console.log(a);
}
}
TempDataStorageService:
var app = angular.module('app');
app.factory('tempDataStorageService', function() {
var savedData = {};
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
EDIT: I have tried to show the declaration of the controller as well, if that helps.
How can I make it so that when I click on the Profile button on VIEW2, it populates VIEW1 with the data?

The plunker:
Working example
The html:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as mainCtrl">
<form>
<h2 class="text-primary">Get data into ng-Model from object in controller</h2>
<hr>
<div class="form-group">
<h3 ng-class="!mainCtrl.firstName? 'text-danger' : 'text-success'">Enter Name</h3>
<input type="text" class="form-control" ng-model="mainCtrl.firstName" placeholder="E.g. Anvika">
</div>
<hr>
<h3 class="text-info">This is what you are typing: {{mainCtrl.firstName}}</h3>
<button type="button" class="btn btn-success" ng-click="mainCtrl.test()">Save Name</button>
</form>
<hr>
<h3 class="text-info">This is what is stored</h3>
<h4>Doctor first name: {{mainCtrl.storedData.doctorFirstName}}</h4>
</body>
</html>
The JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['tempDataStorageService', function(tempDataStorageService) {
var register = this;
register.firstName = "";
register.storedData = tempDataStorageService;
register.test = function () {
tempDataStorageService.setName(register.firstName);
}
}]);
app.factory('tempDataStorageService', function() {
// The service object
var profile = {};
profile.doctorFirstName = "No doctor data stored";
//The functions
profile.setName = function(data) {
profile.doctorFirstName = data;
}
profile.getName = function() {
return profile.doctorFirstName;
}
// return the service object
return profile;
});
Recommendations:
Please properly format code when asking questions.
As good practice use a style guide. A good starting point is John
Papa's Angular Style Guide

Related

Get autocompleted value from input in controller

I have the following in my view:
<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
I am using google maps api for places to autocomplete the input boxes, so if a user starts typing "Lo", he will get a list of places that starts with "Lo" and for example he chooses London.
The problem is in my controller I am not getting the whole autocompleted value. I am only getting what the user initially entered, in this case "Lo".
Here is my controller:
app.controller('BookingsCtrl', function($scope, BookingsService) {
$scope.pickup = "";
$scope.destination = "";
$scope.syncNotification = "";
$scope.calcPrice = function() {
console.log($scope.pickup);
BookingsService.save({
pickup: $scope.pickup,
destination: $scope.destination
}, function(response) {
console.log(response.message);
});
};
});
EDIT:
Here is also a snippet of the JS:
var pickup = document.getElementById('pickup');
var options = {
componentRestrictions: {
country: 'ee'
}
};
var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
pickup.innerHtml = place.formatted_address;
var lat = place.geometry.location.lat();
var long = place.geometry.location.lng();
});
EDIT 2 : Added service
app.service('BookingsService', function ($resource) {
return $resource('http://localhost:3000/', {});
});
EDIT 3 : Template
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="components/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="assets/css/style.css" type="text/css" />
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDt1Y30OssBToIzSCOr3g5IkN3c0D75XVE&libraries=places"
></script>
</head>
<body ng-app='strelsau_client'>
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<img class="masthead-brand" src="../assets/img/logo.png">
<nav>
<ul class="nav masthead-nav">
<li class="active">Home</li>
<li>Contact</li>
</ul>
</nav>
</div>
</div>
<div ng-view>
</div>
</div>
</div>
</div>
<script src="components/jquery/dist/jquery.min.js"></script>
<script src="components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="components/angular/angular.min.js"></script>
<script src="components/angular-route/angular-route.min.js"></script>
<script src="components/angular-resource/angular-resource.min.js"></script>
<script src="js/main.js"></script>
<script src="js/controllers/bookings_controllers.js"></script>
<script src="js/services/bookings_service.js"></script>
</body>
</html>
In fact pickup input element is not getting updated once the place is resolved.
The problem with this function:
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
pickup.innerHtml = place.formatted_address; //invalid
//...
});
For setting input field value should be used value property.
Anyway, given the example, try to replace it with:
(function (scope) {
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
scope.pickup = place.formatted_address;
});
})($scope);
Example
angular.module('myApp', [])
.controller('BookingsCtrl', function ($scope) {
$scope.pickup = "";
$scope.destination = "";
$scope.syncNotification = "";
var pickup = document.getElementById('pickup');
var options = {
componentRestrictions: {
country: 'ee'
}
};
var autocompletePickup = new google.maps.places.Autocomplete(pickup, options);
(function (scope) {
google.maps.event.addListener(autocompletePickup, 'place_changed', function () {
var place = autocompletePickup.getPlace();
scope.pickup = place.formatted_address;
});
})($scope);
$scope.calcPrice = function () {
console.log($scope.pickup);
alert($scope.pickup);
/*BookingsService.save({
pickup: $scope.pickup,
destination: $scope.destination
}, function (response) {
console.log(response.message);
});*/
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div ng-app="myApp" ng-controller="BookingsCtrl" ng-cloak>
<label for="txtFrom">Pickup Location</label>
<input type="text" id="pickup" placeholder="Address, aiport, train station, hotel..." ng-model="pickup">
<label for="txtDestination">Destination</label>
<input type="text" id="destination" placeholder="Address, aiport, train station, hotel..." ng-model="destination">
<input class="btn btn-success" name="calcPrice" id="calcPrice" type="submit" value="Calculate Price" ng-click="calcPrice()">
</div>

ng-options not updating select tag

In the following code taken from my app, the dropdown is not getting updated with the scope data. How can I make this work? I need to pass the dropdown options from parent controller to child controller. I am getting [$injector:modulerr] error.
<div ng-app="myApp" ng-controller="parentCtrl as pt">
<button ng-click="pt.callChild()">Change Dropdown</button>
<div ng-controller="childCtrl as ct">
<select ng-model="ct.selectedName" ng-options="item for item in ct.names">
</select>
</div>
</div>
JS:
var app = angular.module('myApp', []);
app.controller('parentCtrl', function ($scope) {
var vm = this;
var newArray = ["Steve", "Jony"];
vm.callChild = function () {
$scope.$broadcast('someEvent', newArray);
};
});
app.controller('childCtrl', function ($scope) {
var vm = this;
vm.names = ["Emil", "Tobias", "Linus"];
$scope.$on('someEvent', function (e, newArray) {
vm.names = newArray;
});
});
Here is the fiddle.
The code is working fine for me and I have incorporated angular 1.5 version.
See plnkr here .
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
<script src="app.js"></script>
</head>
<div ng-app="myApp" ng-controller="parentCtrl as pt">
<button ng-click="pt.callChild()">Change Dropdown</button>
<div ng-controller="childCtrl as ct">
<select ng-model="ct.selectedName" ng-options="item for item in ct.names">
</select>
</div>
</div>
</html>

Getting data from metaweather API to angularjs page

I'm building a simple weather app that gets the weather for any city.
For this API there are two stages:
1) you enter a name of a city, get its "where on earth ID" (woeid).
2) use the woeid to search for the weather.
This is the API: https://www.metaweather.com/api/
For example:
https://www.metaweather.com/api/location/search/?query=london
You get this JSON:
[{"title":"London","location_type":"City","woeid":44418,"latt_long":"51.506321,-0.12714"}]
For starters, just to get the woeid would be great.
It fails to connect to the API but when i type it manually it works.
app.js:
var app = angular.module('weatherApp', []);
app.controller('weatherCtrl', ['$scope', 'weatherService', function($scope, weatherService) {
function fetchWoeid(city) {
weatherService.getWoeid(city).then(function(data){
$scope.place = data;
});
}
fetchWoeid('london');
$scope.findWoeid = function(city) {
$scope.place = '';
fetchWoeid(city);
};
}]);
app.factory('weatherService', ['$http', '$q', function ($http, $q){
function getWoeid (city) {
var deferred = $q.defer();
$http.get('https://www.metaweather.com/api/location/search/?query=' + city)
.success(function(data){
deferred.resolve(data);
})
.error(function(err){
console.log('Error retrieving woeid');
deferred.reject(err);
});
return deferred.promise;
}
return {
getWoeid: getWoeid
};
}]);
index.html:
<!DOCTYPE html>
<html ng-app="weatherApp">
<head>
<meta charset="utf-8" />
<title>Weather App</title>
<link data-require="bootstrap-css#3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script>document.write('<base href="' + document.location + '" />');</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script data-require="jquery#*" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="weatherCtrl">
<form>
<div class="form-group">
<input class="form-control" type="text" ng-model="city" placeholder="e.g. london" />
<input class="btn btn-default" type="submit" value="Search" ng-click="findWoeid(city)" />
</div>
</form>
<p ng-show="city">Searching the forecasts for: {{city}}</p>
<div>
<h1>WOEID is: {{ place }}</h1>
<a ng-click="findWeather('london'); city = ''">reset</a>
</div>
</body>
</html>
It appears you are having a Cross Origin problem. It doesn't look like Metaweather supports JSONP, so the fix for this is a bit more complex. You need to be running your page through a server that can support a proxy. One such example is https://www.npmjs.com/package/cors-anywhere. If you set that up using the defaults then change your AJAX call to:
$http.get('http://localhost:8080/https://www.metaweather.com/api/location/search/?query=' + city)

How to save input text to variable while typing in angularjs

Can anyone tell me how can I do that please?
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.0-rc.2/angular.js" data-semver="1.4.0-rc.2"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<form name="form.one" ng-submit="submitForm()">
<input ng-model="name">
<input type="submit">
</form>
<p>Hello {{name}}!</p>
</body>
And my app.js is
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = "Name";
var data = {};
$scope.submitForm = function() {
var data = form.one.name;
};
});
How can I save input to the data variable? Is it possible to save on keypress?
To use your form with Angular, there's a few modifications you need to make for this code to work: first, you need to add the novalidate attribute to your form; it is used to disable the browser's native form validation. Angular will use it's own validation. Here's a few other modifications (they're explained in detail here):
<body ng-controller="MainCtrl">
<form novalidate>
<input ng-model="name">
<!-- The method for submitting the data goes on the button. -->
<!-- The name is passed to the method you want to use to store the data, which you make happen when the button is clicked by using the ngClick directive. -->
<input type="submit" ng-click="submitForm(name)" value="Click me!">
</form>
<p>Hello {{name}}!</p>
<!-- This bit of code is to display the results of adding names to the array in the browser window: -->
<pre>{{ data }}</pre>
</body>
Here's the Javascript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = "Name";
// I put the data array in the $scope so it can be displayed in the browser window and you can see the results:
$scope.data = [];
// Now, whenever the button is clicked, this method is run.
// It then stores the name in the 'data' array defined above.
$scope.submitForm = function(name) {
$scope.data.push(name);
};
});
Try this for it to show straight after typing:
<body ng-controller="myApp">
<input type="text" ng-model="name">
<p>Hello {{name}}!</p>
</body>
Javascript:
var myApp = angular.module('myApp',[]);
myApp.controller('myApp', function ($scope) {
$scope.name = $scope.name;
console.log($scope.name)
});
Small little JSFiddle for this:
https://jsfiddle.net/joshdmiller/HB7LU/

ng-submit in angularJs is not working

I am relatively new in angularJs. I am working with a search field where search will execute with the "ng-submit", but ng-submit is not working. Here is my template (only the search portion):
<form class="navbar-form navbar-right" ng-submit="search()">
<input class="form-control col-lg-8" type="text" placeholder="Search" ng-model="term"></input>
</form>
and the associated angularJS
<script>
app.controller("NavCtrl", ['$scope', '$http', '$location', '$q','$timeout', function NavCtrl($scope, $http, $location, $q, $timeout) {
$scope.results = ["Test"];
$scope.term = "";
$scope.reqs = "5";
$scope.pics = "45";
$scope.ddata = "asdasd";
$scope.ddata = $http.post("{% url 'get-nav-info' %}").success(
function(result){
//$scope.reqs = result.data.data.num_request;
//$scope.pics = result.data.data.num_photo;
return result.data;
}
);
//$scope.reqs = $scope.ddata.num_request;
//$scope.pics = $scope.ddata.num_photo;
$scope.search = function(){
//alert("test");
//$location.absUrl()
//$location.path("{% url 'search-term-show' %}?term="+$scope.term).replace();
$http.get("{% url 'search-term-show' %}?term="+$scope.term).success(function(result){
return result.data;
});
//$scope.$apply();
}
}]);
</script>
I am pretty sure the problem is occurring in the angularJs ng-submit portion. But can't fix it out properly. I am pretty sure because if I manually write the url for search then it shows results but if I try to search the result by pressing enter the search gives no response. Please help me to fix this problem.
Well there is a lot of useless code up there, but i created a plunker
http://plnkr.co/edit/uwDrNRLxUBLQdoi2ykez?p=preview
EDIT: SORRY posted wrong link!
which gives some advice, maybe you forgot to attach the controller to your html like ng-controller="navController"
var app = angular.module('myApp', []);
app.controller('navController', ['$scope', '$http', function($scope, $http) {
$scope.search = function() {
console.log("search")
$http.get($scope.term).success(function(result) {
window.console.log("result");
return result.data;
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="http://code.angularjs.org/1.2.1/angular.js" data-semver="1.2.1"></script>
<script src="script.js"></script>
<body ng-app="myApp">
<div ng-controller="navController">
<form ng-submit="search()">
<input class="form-control col-lg-8" type="text" placeholder="Search" ng-model="term"></input>
<input type="submit">
</form>
</div>
</body>
<html>
On submit it does the search, but i cannot tell what that url is because u used some kind of template mixin, please avoid mixing template and Javascript
Have you put id="anyName" to tag?
If so it should work
Thanks,
Sameer
You can try to insert into the 'form' with type = "submit" button to the action and leaves it hidden.
this eg:
<button type="submit"
data-ng-hide="true"
data-ng-click="save()"/>
Here is index.html:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="jquery#*" data-semver="2.1.3" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<link data-require="bootstrap#3.3.1" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script data-require="bootstrap#3.3.1" data-semver="3.3.1" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js" data-semver="1.3.7" data-require="angular.js#*"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="NavCtrl">
<form ng-submit="search()">
<input class="col-xs-9" type="text" placeholder="Search" ng-model="term" />
<input type="submit" ng-submit="search()" />
</form>
</div>
</body>
</html>
I left the original get and post requests alone, except that I changed it so that it would return a promise. I couldn't get the original search working because I wasn't sure what it was trying to accomplish. I cleaned up the project, employed some "best practices", and got the angular directives working. This won't benefit the person who submitted the question, but might help somebody else coming along with a similar problem. Here is the script file:
(function(){
var app = angular.module('myApp', []);
app.controller('NavCtrl', NavCtrl);
function NavCtrl($scope, $http, $location) {
$scope.results = ["Test"];
$scope.term = "";
$scope.reqs = "5";
$scope.pics = "45";
$scope.ddata = "asdasd";
$scope.ddata = $http.post("{% url 'get-nav-info' %}").then(
function(result) {
// $scope.reqs = result.data.data.num_request;
// $scope.pics = result.data.data.num_photo;
return result.data;
});
//$scope.reqs = $scope.ddata.num_request;
//$scope.pics = $scope.ddata.num_photo;
$scope.search = function() {
alert("search function was called");
//alert("test");
$location.absUrl();
$location.path("{% url 'search-term-show' %}? term="+$scope.term).replace();
$http.get("{% url 'search-term-show' %}?term="+$scope.term)
.then(function(result) {
//Successful
console.log(result.data);
},
function() {
//Error
console.log("Could not locate term.");
});
return result.data
};
}
})();
Had the same problem and ngSubmit seems to work better with objects, convert your ng-model to foo.term and access it in the controller as $scope.foo.term.
This will work.
To test if you're binding correctly,
Underneath the input, do something like {{ foo.term }} and see value updating

Resources