ng-submit in angularJs is not working - angularjs

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

Related

How to set session value in angular js

Am beginner in learning angular js,I need to know how to set the session values like user id, mail,username etc..
kindly tell me the efficient ways to set session values in angular js
thank you in advance
Reference link reference link
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', ["ngStorage"])
app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
$scope.Save = function () {
$localStorage.LocalMessage = "LocalStorage: My name is Mudassar Khan.";
$sessionStorage.SessionMessage = "SessionStorage: My name is Mudassar Khan.";
}
$scope.Get = function () {
$window.alert($localStorage.LocalMessage + "\n" + $sessionStorage.SessionMessage);
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<input type="button" value="Save" ng-click="Save()" />
<input type="button" value="Get" ng-click="Get()" />
</div>
</body>
</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 the state of check box to local storage using AngularJS?

I want to save the current state of check box and reload it when open the page next time.
AngularJS:
var app = angular.module('MyApp', []);
app.controller('MyController', function ($scope, $window) {
var init = function () {
$scope.check = $window.localStorage.getItem("app3");
};
init();
$scope.Save = function () {
$window.localStorage.setItem("app3", $scope.check);
}
});
HTML:
<html ng-app="MyApp" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="angular-1.4.9.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MyController">
<input id="check1" type="checkbox" ng-model="check" />
<input type="button" value="Save" ng-click="Save()" />
</div>
</body>
</html>
Dont use jquery with angular.
Attach a ng-model to your input box like so : and you can access the value of the input in your controller using $scope.check
your local storage setting will be like so :
$window.localStorage.setItem('app3',$scope.check);
Thats it! Kindly go through angular tutorials or their documentation to understand how angular works.

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

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

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/

Resources