How to add a variable element into the url in AngularJS $http - angularjs

I have the below code to pull the weather forecast. How do I make the zip code within the url as variable. I have done this in simple javascript by breaking down the url to substrings and then passing then in the get method but that is not working in AngularJS. Please help.
JS code
controllers.weatherCtrl= function ($scope,$http) {
$scope.getWeather=function() {
$http.get('http://api.openweathermap.org/data/2.5/forecast?zip=60007&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
.then(function(response){
$scope.weatherdata=response.data;
});
};
};
Index.html
<div class="container border">
<input ng-model="zip">
<button class="btn" ng-click="getWeather()">Get Weather</button>
<br>
<span>{{weatherdata.city.name + ', ' + weatherdata.city.country}}</span>
</div>

You would need to add in a parameter to the weatherCtrl function and add that to variable to the URL. Then you call the function with the parameter.
JS code
controllers.weatherCtrl= function ($scope,$http) {
$scope.getWeather=function(zipcode) {
$http.get('http://api.openweathermap.org/data/2.5/forecast?zip='+zipcode+'&appid=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
.then(function(response){
$scope.weatherdata=response.data;
});
};
};
Index.html
<div class="container border">
<input ng-model="zip">
<button class="btn" ng-click="getWeather(zip)">Get Weather</button>
<br>
<span>{{weatherdata.city.name + ', ' + weatherdata.city.country}}</span>
</div>

If you create the url, then Mark S's answer is the correct one. if you receive the url from somewhere and you have to parse it and extract the zip code, you can use a regex match
url.match(/(?<=zip\=)\d*(?=\&)/g)
being url the url string.

Related

call function pass value of div as parameter

I need to call a function from my html page then using the div content as the parameter.
Angular Code (.js file)
$scope.foo = function(url) {
console.log(url);
};
.html file
<span ng-click="foo(t.ticketId)">
<div>
ThisIsTheOutput
</div>
</span>
what i am getting now is undefined. Help please!!

$location.path not working

I am working on angularjs form where I need to navigate to other template on click on anchor tag. ng-click is working but problem is with $location.path.
here is main template
Forgot Password
Now on its controller I have mentioned same method name
$scope.ShowForgotPasswordForm = function () {
$location.path("/forgotpasswordform");
};
Now main controllerjs and forgotpasswordform form both are in same folder.
Then I added this form to directive js file which is again in same folder.
angularFormsApp.directive('forgotpasswordform',
function () {
var baseurl = window.location.protocol + "//" + window.location.host + "/";
return {
restrict: 'E',
templateUrl: baseurl + 'app/Login/forgotPasswordForm.html'
}
});
and template for forgot password is as below, which is also in same folder
<!--ForgotPassword Form Start-->
<div class="container-fluid">
<div class="row-fluid">
<form class="form-signin padding mg-tb200" novalidate name="forgotpasswordform" role="form">
<h3 class="line-btm">Forgot Password</h3>
<p class="lh20">
Please enter a valid email ID in the text field below,
if it matches our database, a password reset link
will be sent on this email ID.
</p>
<input type="email" class="form-control log-input" placeholder="Email address" required autofocus>
<div class="checkbox">
<button class="btn-submit right" type="submit">Submit</button>
</div>
</form>
</div>
</div>
<!--ForgotPassword Form End-->
But when I click on anchor tag its going to function ShowForgotPasswordForm
but not navigating to form.
Use window.location.pathname then, if $location is not undefined it should work.
So there are a few problems with your code.
First it looks like you have a conceptual mistake that the directive name is linked with the URL path. This is not the case.
But you can link them using a router such as the Component-Router, uiRouter or ngRouter.
Lets take a look at how this would look using uiRouter:
We add change your link to use the uiRouter state reference directive
<a ui-sref="forgotPassword"
class="forgot-txt"
ng-show="loginUser.typeofUser == 'ExternalUser'">
Forgot Password
</a>
We will replace your directive with a controller. I won't include the code here.
Now we will define a state configuration:
forgotPasswordStateConfig.$inject = ['$stateProvider'];
function forgotPasswordStateConfig($stateProvider) {
$stateProvider
.state('forgotPassword', {
url: 'forgotpassword',
templateUrl: 'app/Login/forgotPasswordForm.html',
controller: 'ForgotPasswordCtrl as ctrl'
});
}
app.config(forgotPasswordStateConig);

Updating and deleting one record within object

I'm trying to create a system in which I can display, edit and delete information on players and teams using angular along with a RESTful API. I have the parts working in which I show all the data and post data to the database.
The part I am having trouble with is updating data as I can't manage to get the http put working with the correct data being sent.
HTML
<script type="text/ng-template" id="team-single.html">
<div class="team-box">
<div class="badge">
<img ng-src="images/{{x.club_name}}.png" width="100" height="100"></div>
<div ng-hide="editorEnabled">
<div class="team-name">{{x.club_name}}</div>
<p><b>Manager:</b> {{x.club_manager}}</p>
<p><b>Ground:</b> {{x.club_ground}}</p>
<p><b>Nickname:</b> {{x.club_nickname}}</p>
<div class="team-p">{{x.club_info}}</div>
Edit Team
</div>
<div ng-show="editorEnabled">
<p><input ng-model="x.club_name"></p>
<p><input ng-model="x.club_manager"></p>
<p><input ng-model="x.club_ground"></p>
<p> <input ng-model="x.club_nickname"></p>
<p><input ng-model="x.club_info"></p>
<input type="hidden" name="id" ng-value="" />
Save
</div>
</script>
<div class="row teams">
<div class="container">
<div class="col-md-4" ng-repeat="x in teams" ng-include="'team-single.html'"></div>
</div>
JS
var app = angular.module('footballApp', []);
app.controller("TeamCtrl", function ($scope, $http) {
$scope.updateTeam = function () {
$http({
method: 'PUT',
url: 'clubs.php/teams/' + id,
data: ??,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
};
});
I have enabled an editor on the front end to edit the fields. I don't know how to pass the one object being edited back into the updateTeam function while not passing the entire team array.
Also in the HTTP PUT, I have to use the id field of the relevant club in the URL but I'm not sure how to send this back.
Any help would be greatly appreciated.
To solve your problem you might need to rethink your UI. Why do you want to show edit option for all teams at once in the UI. Ideally you should show the team details along with an option to edit them.
When user click on edit call a function with team data and then show a form where those details can be edited and later can be send for submission.
Refer to this plnkr example https://plnkr.co/edit/muqnmIhO77atLyEHS9y7?p=preview
<div class="row">
<div class="col-xs-6 col-lg-4" ng-repeat="team in teams">
<h2>{{ team.club_name }}</h2>
<p>{{ team.club_info }}</p>
<p><a class="btn btn-default" ng-click="onEditDetails(team)" href="javascript:void(0);" role="button">Edit details ยป</a></p>
</div>
</div>
and then in controller
$scope.onEditDetails = function(team) {
$scope.team = team;
};
This will give you the reference of current selected team. You can use $scope.team then to show a form in UI which can be submitted along with its new edited data.
Note: In your example you are using a template to show HTML in UI but since they are in a ng-repeat each of your template will be using the last variable of loop. A template included using ng-include doesn't create a different scope for each of your team in teams.
If you want to create reusable HTML (though un-necessary as per your requirement) you can create a directive and include it in your ng-repeat as <my-team-directive data="x"></my-team-directive>

How get access to variable in Angular JS?

I have next Angular JS controllers structure:
<div ng-controller="MainController">
<div ng-controller="mainCtrlTst">
// here is loaded HTML file
</div>
</div>
HTML file:
<div ng-controller="MainController">
<input ng-model="formData.map" value="">
</div>
For default formData.map containts address "USA, New York"
I have method Save() in MainController, but when I call this method I get:
console.log(formData.map); // undefined
How I can get value formData.map from input?
You should declare your model in controller like
$scope.formData = {
map: ''
};
And then use it in the view.
And then check in the save method by following code
console.log($scope.formData.map);
Hope you will not get undefined.
Try the following in MainController:
console.log($scope.formData.map);
To be more precise, in your save() function inside the controller do as follows:
$scope.save = function(){
console.log($scope.formData.map);
}
To know more about $scope, visit : https://docs.angularjs.org/guide/scope

AngularJS invoke Controller function

sorry for the rather basic question but I am really a beginner developing in AngularJS.
So I have a conteoller like this (like explaned here: https://github.com/johnpapa/angular-styleguide):
(function() {
'use strict';
angular
.module('project.management')
.controller('ManagementController', ManagementController);
function ManagementController() {
var vm = this;
vm.getUsersBySearchString= getUsersBySearchString;
////////////
function getUsersBySearchString(searchString) {
alert('get User By searchstring: ' + searchString);
}
};
})();
Now I have a HTML fragment in my template and I really don't know how to invoke function getUsersBySearchString(searchString). I have tried this one:
<div ng-controller="vm">
<form class="well form-search">
<label>Usersuche:</label>
<input type="text" ng-model="term" class="input-medium search-query" placeholder="Username">
<button type="submit" class="btn" ng-click="getUsersBySearchStringgetUsersBySearchString()">Suchen</button>
</form>
<pre ng-model="result">
{{result}}
</pre>
</div>
but I don't know what to put here
<div ng-controller="vm">
and how to invoke the method.
Thanks a lot for help!
<div ng-controller="vm">
That is incorrect. You have no controller named "vm". Your controller is named ManagementController.
The syntax for your use-case is
<div ng-controller="ManagementController as vm">
And to invoke the function, you would use
ng-click="vm.getUsersBySearchString(term)"
Note that the alias you choose in the HTML has no relationship with the alias you chose for thisin the controller code. You might very well use
<div ng-controller="ManagementController as managementCtrl">
and
ng-click="managementCtrl.getUsersBySearchString(term)"

Resources