I am trying to submit form on ng-submit event but form submit is not working.
$http,$state,dtoResource are injections
where dtoResource is factory which modify json data.
My code is as below
index.html
<!DOCTYPE html>
<html ng-app="autoQuote">
<head lang="en">
<meta charset="UTF-8">
<title>Angular Js DTO mgnt</title>
<!-- Style sheets -->
<link href="css/bootstrap.css" rel="stylesheet"/>
<link href="css/app.css" rel="stylesheet"/>
<!-- Library Scripts -->
<script src="js/jquery.js"></script>
<script src="js/angular.js"></script>
<script src="js/angular-ui-router.js"></script>
<!-- Application Script -->
<script src="app/app.js"></script>
<!-- Services -->
<script src="common/services/common.services.js"></script>
<script src="common/services/dtoResource.js"></script>
<!-- Controllers -->
<script src="app/ctrl/autoQuoteCtrl.js"></script>
<script src="app/ctrl/questionsCtrl.js"></script>
</head>
<body>
<ul>
<li>step 1
<li>step 2
</ul>
<div class="container">
<div ui-view=""></div>
</div>
</body>
</html>
step1.html
Email:
autoQuoteCtrl.js
(function () {
"use strict";
angular
.module("autoQuote")
.controller("autoQuoteCtrl", ["$http","$state","dtoResource",autoQuoteCtrl]);
function autoQuoteCtrl($http,$state,dtoResource) {
console.log('We are in form');
//self = this;
// if valid (check form validate true)
//console.log(dtoResource);
//call function from your service, and do something with it
dtoResource.rc1Step1DTO();
$http({
method : 'POST',
url : 'api.php',
data : { dtoObj: JSON.stringify(prepareAutoQuoteDTO.postAutoQuoteObj) }, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
console.log(data);
if (!data.success) {
} else {
// if successful, bind success message to message
//$scope.message = data.message;
}
});
}
}());
dtoResource.js
(function () {
"use strict";
angular
.module("autoQuote")
.factory("dtoResource",
["$resource",
dtoResource]);
console.log('inside dtoResource');
function dtoResource(){
var prepareAutoQuoteDTO = {
postAutoQuoteObj : $.getAutoQuoteObject(),
initializeDriverObj: function(){
var driverLocObj = new Driver();
driverLocObj.PersonInfo = new PersonInfo();
driverLocObj.DriverLicense = new DriverLicense();
driverLocObj.Incident = new Incident();
return driverLocObj;
},
initializeAppInfo: function(){
var appInfoLocObj = new ApplicationInfo();
appInfoLocObj.Discount = new Discount();
return appInfoLocObj;
},
/*
* Initialize Vehicle object for autoQuoteDTO.js
*/
initializeVehicleObj: function(){
var vehicleLocObj = new Vehicle();
return vehicleLocObj;
},
/*
* store session info
*/
rc1Step1DTO: function(){
var emailId = $('#save_quote_email').val();
if (typeof emailId !== "undefined" && emailId && emailId != '' && emailId != 'Email Address'){
var email = new Email();
email.EmailTypeCd = 'PRIMARY';
email.EmailAddress = emailId;
this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo = this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo || new Contact();
this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails = [];
this.postAutoQuoteObj.ApplicationInfo.GeneralPartyInfo.ContactInfo.Emails.push(email);
}
}
};
return prepareAutoQuoteDTO;
}
}());
You have to add ng-app and ng-controller attributes to parent DOM elements.
And you can not invoke controller's instance in ng-submit :)
You should add special method in the controller, and call that one.
Something like this
<body ng-app>
<div ng-controller="autoQuoteCtrl">
<form ng-submit="onSubmit()">
...
</form>
</div>
</body>
And your controller something like this
angular
.module("autoQuote")
.controller("autoQuoteCtrl", ["$http","$state","dtoResource", function($http, $state, dtoResource) {
$scope.onSubmit = function() {
alert('hi, I was invoked on form submit');
};
}]);
PS: In this example I am using co called scope soup. It is simple to understand but it clusters the $scope with additional properties. It is not recommended approach now. Read about better approach here: http://www.technofattie.com/2014/03/21/five-guidelines-for-avoiding-scope-soup-in-angular.html
UPDATE
You have slight confusion in your code:
The route redirected to /, which was caught by questionsCtrl, but the relevant template had attribute ng-controller=autoQuoteCtrl. So which controller should be then used to respond to user action?? Not sure if that was intended :)
SOLUTION
The submit function should have been called like this
<form ng-submit="onSubmit()">
I forgot the () in the first example, sorry :)
html
<div ng-controller="formCtrl">
<form name="userForm" class="well form-search" >
<input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" required >
<input type="email" ng-model="email" class="input-medium search-query" placeholder="Email" required >
<input type="text" ng-model="message" class="input-medium search-query" placeholder="Message" required >
<button type="submit" class="btn" ng-click="formsubmit(userForm.$valid)" ng-disabled="userForm.$invalid">Submit </button>
</form>
<pre ng-model="result">
{{result}}
</pre>
</div>
jsfile
var app = angular.module('formExample', []);
app.controller("formCtrl", ['$scope', '$http', function($scope, $http) {
$scope.url = 'submit.php';
$scope.formsubmit = function(isValid) {
if (isValid) {
$http.post($scope.url, {"name": $scope.name, "email": $scope.email, "message": $scope.message}).
success(function(data, status) {
console.log(data);
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
})
}else{
alert('Form is not valid');
}
} }]);
click here
Related
I am new to angular but have created a fairly simple app. I have looked through other, similar questions but I don't see any obvious spelling mistakes.
in my html file
<div ng-controller="OutcomeController" data-ng-init= "init()">
<div class="title">
<h1>Runs</h1>
<br/>
</div>
<table width="98%">
<tr>
<td>
<div class="searchPlace">
<form ng-submit="showCprRequest()" class= "search-form">
<input type="text" class="search-input" ng-model="idText"
placeholder="Search Id" autofocus>
<button type="submit" class="search-submit" >Search</button>
</form>
</div>
</td>
</tr>
</table>
In my outcomes.js file
function OutcomeController ($scope, $rootScope, $location ,$http, $log, $routeParams, diceService) {
$scope.init = function () {
// get id from url parameter (html head part)
$scope.id=$routeParams.id;
console.log('here');
// if id already entered on the page, get it from there
if ($scope.iIdText != null && $scope.idText != undefined && $scope.idText != "") {
$scope.showCprRequest();
}
else if ($scope.id == null || $scope.id == undefined) {
$scope.showDefaultCprRequest();
}
else {
$scope.iIdText = $scope.id;
$scope.showCprRequest();
}
$scope.showCprRequest = function () {
if ($scope.IdText.length == 0) {
console.log('or there');
return;
}
console.log('here');
var requestUrl = baseUrl+ "/cpr/" + $scope.id;
$http({method: "GET", url: requestUrl}).
success(function (data, status) {
$scope.diceRequestDisplays = data;
$scope.itemsPerPage = $scope.totalItems;
}
});
};
angular.module('outcome', []).controller('OutcomeController', OutcomeController);
NONE of the console.logs are getting hit, and the error I get is that OutcomeController is not registered. But I do so on the bottom line correct? Is there anything obvious I am missing?
Because you did not add ng-app and CDN for the angular router.
We can use CDN or we can install an angular route using npm install.
the console is printed properly you need to add $scope.showDefaultCprRequest() because there is no function related to that.
You can find angular all the CDN from here:
https://cdnjs.com/libraries/angular.js/1.4.0
HTML:
<!doctype html>
<html ng-app="App">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0/angular-route.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div ng-controller="OutcomeController" ng-init= "init()">
<div class="title">
<h1>Runs</h1>
<br/>
</div>
<table width="98%"><tr>
<td>
<div class="searchPlace">
<form ng-submit="showCprRequest()" class= "search-form">
<input type="text" class="search-input" ng-model="idText" placeholder="Search Id" autofocus>
<button type="submit" class="search-submit" >Search</button>
</form>
</div>
</td>
</tr></table>
</div>
</body>
</html>
js:
var app = angular.module('App',['ngRoute']);
app.controller('OutcomeController', ['$scope', '$rootScope', '$location' ,'$http', '$log', '$routeParams', function ($scope, $rootScope, $location ,$http, $log, $routeParams)
{
$scope.init = function () {
// get id from url parameter (html head part)
console.log('here');
$scope.id=$routeParams.id;
// if id already entered on the page, get it from there
if ($scope.iIdText != null && $scope.idText != undefined && $scope.idText != "") {
$scope.showCprRequest();
}
else if ($scope.id == null || $scope.id == undefined) {
$scope.showDefaultCprRequest();
}
else {
$scope.iIdText = $scope.id;
$scope.showCprRequest();
}
$scope.showCprRequest = function () {
if ($scope.IdText.length == 0) {
console.log('or there');
return;
}
console.log('here');
var requestUrl = baseUrl+ "/cpr/" + $scope.id;
$http({method: "GET", url: requestUrl}).
success(function (data, status) {
$scope.diceRequestDisplays = data;
$scope.itemsPerPage = $scope.totalItems;
})
};
};
}]);
I have a mysql database/node backend, connected to an Angular frontend, that I am querying, specifically to send it the data from 3 simple text inputs in a form.
I believe my error is quite trivial for anyone with node/angular experience because I can successfully send my database input from one of the text inputs; however, when I try to detect and send data from all three inputs, it only sends the data from whichever input has its matching controller function as the last one (of the three) in my script.
Here is my html file and the script
var button = document.getElementById("clickButton");
const app = angular.module('app',[]);
app.service('appService', ['$http', function($http){
return {
'getSuggestion' : function(suggestion,callback){
$http.post('/getSuggestion', {
'suggestion': suggestion
}).success(function (response) {
callback(response);
})
.error(function (data, status, header, config) {
callback({
'error': true,
'message': "Something went wrong."
});
});
}
}
}]);
app.controller('app', function($scope,appService) {
//message send Function
$scope.$watch('messageInput', function (newValue, oldValue) {
//null check
if (newValue !== null) {
//wait for the button to be pressed
button.onclick = function() {
alert("USERNAME");
//call server query function
appService.getSuggestion(newValue, function (response) {
$scope.suggestionCollection = response.rows;
});
};
}
});
$scope.$watch('messageInput2', function (newValue, oldValue) {
//null check
if (newValue !== null) {
//wait for the button to be pressed
button.onclick = function() {
alert("PASSWORD");
//call server query function
appService.getSuggestion(newValue, function (response) {
$scope.suggestionCollection = response.rows;
});
};
}
});
$scope.$watch('messageInput3', function (newValue, oldValue) {
//null check
if (newValue !== null) {
//wait for the button to be pressed
button.onclick = function() {
alert("PASSWORD");
//call server query function
appService.getSuggestion(newValue, function (response) {
$scope.suggestionCollection = response.rows;
});
};
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app" ng-controller="app">
<head>
<title>Node app</title>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="formFields">
<form class="defaultForm" id="loginForm">
<input class="loginField" type="text" name="username" ng-model="messageInput" placeholder="username"> <br>
<input class="loginField" type="text" name="password" ng-model="messageInput2" placeholder="password"> <br>
<input class="loginField" type="text" name="username" ng-model="messageInput3" placeholder="pass conf"> <br>
<button id="clickButton" class="submitButton">submit</button>
</form>
</div>
<!--<script src="Scripts/login.js"></script>-->
<script src="js/angular.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
You have a $watch for each input, and you have a submit() for each input. This is why you send only the input that changed. If you want to send them all together you should hold one submit(), means one onClick() that will check all new values are not null and send them to the server, something like this:
$scope.$watch('allInput', function (newValues, oldValues) {
//null check
if (newValues.user !== null && newValues.pass !== null && newValues.pass2 !== null) {
//wait for the button to be pressed
button.onclick = function() {
alert("USERNAME");
alert("PASSWORD");
alert("PASSWORD CONF");
//call server query function
appService.getSuggestion(newValues, function (response) {
$scope.suggestionCollection = response.rows;
});
};
}
});
and the html:
<form class="defaultForm" id="loginForm">
<input class="loginField" type="text" name="username" ng-model="allInput.name" placeholder="username"> <br>
<input class="loginField" type="text" name="password" ng-model="allInput.pass" placeholder="password"> <br>
<input class="loginField" type="text" name="username" ng-model="allInput.pass2" placeholder="pass conf"> <br>
<button id="clickButton" class="submitButton">submit</button>
</form>
Of course getSuggestion() will change as well:
app.service('appService', ['$http', function($http){
return {
'getSuggestion' : function(data,callback){
$http.post('/getSuggestion', {
'name': data.name,
'pass': data.pass,
'pass2': data.pass2
}).success(function (response) {
callback(response);
})
.error(function (data, status, header, config) {
callback({
'error': true,
'message': "Something went wrong."
});
});
}
}
If I understand your question correctly, you want to watch for changes of values in all three input fields. If user types anything in any one of the three input fields, you want to send the values from all three input fields to your backend. And when user hits "Submit", you want to get values from all three input fields as well.
To solve this problem, you need two pieces:
set up a persistent click event handler on the button, as opposed to adding one only when some change happens. Note that in your code, you are updating this click handler each time one of the three input fields changes. This would cause the new input handler to overwrite the old one. That's why you only get the last touched value. I would recommend looking into the ng-click directive.
get inputs from all three form fields when any one of them is changed. This can be achieved through the ng-change directive. Or alternatively, you can put all three ngModels under one parent object and just $watch() that one parent object, as Hatzav Wolff suggests in his answer.
Here is how I would approach it:
var button = document.getElementById("clickButton");
const app = angular.module('app',[]);
app.service('appService', ['$http', function($http){
return {
'getSuggestion' : function(suggestion,callback){
$http.post('/getSuggestion', {
'suggestion': suggestion
}).success(function (response) {
callback(response);
})
.error(function (data, status, header, config) {
callback({
'error': true,
'message': "Something went wrong."
});
});
}
}
}]);
app.controller('app', function($scope,appService) {
$scope.handleChange= function() {
/* Do whatever you want with the input. They are all here */
console.log($scope.messageInput + ' ' + $scope.messageInput2 + ' ' + $scope.messageInput3);
}
$scope.handleSubmit= function() {
/* Do whatever you want with the input. They are all here */
console.log($scope.messageInput + ' ' + $scope.messageInput2 + ' ' + $scope.messageInput3);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app" ng-controller="app">
<head>
<title>Node app</title>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="formFields">
<form class="defaultForm" id="loginForm">
<input class="loginField" type="text" name="username" ng-model="messageInput" ng-change="handleChange()" placeholder="username"> <br>
<input class="loginField" type="text" name="password" ng-model="messageInput2"ng-change="handleChange()" placeholder="password"> <br>
<input class="loginField" type="text" name="username" ng-model="messageInput3" ng-change="handleChange()" placeholder="pass conf"> <br>
<button id="clickButton" ng-click="handleSubmit()" class="submitButton">submit</button>
</form>
</div>
<!--<script src="Scripts/login.js"></script>-->
<script src="js/angular.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
I just can't get it working no matter what I do. Been sitting for hours and nothing. After submitting form I create local storage of values name, surname, email, so that I would be able to use them to fill up form so that user would not have to type them everytime.
submit() is in review.controller.js
(function () {
'use strict';
angular.module('app').controller('ReviewController', ReviewController);
ReviewController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$route','$cookies','localStorageService'];
function ReviewController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$route,$cookies,localStorageService) {
var vm = this;
vm.name = null;
vm.surname = null;
vm.Email = null;
vm.review = null;
vm.allgenres = [];
vm.submit = submit;
vm.allreviews = [];
$scope.localArray=[];
loadAllReviews();
submit();
$scope.templates = [{ name: 'man.main.view.html', url: 'main/main.view.html'}];
$scope.template = $scope.templates[0];
function loadAllReviews() {
UniversalService.GetAllReviews()
.then(function (review) {
vm.allreviews = review;
});
}
$scope.init = function () {debugger;
// $scope.$MainController.obtained_array = localStorage.getItem("storageKey");debugger;
$scope.storageKey = localStorage.getItem("storageKey");debugger;
};
$scope.storageKey = localStorage.getItem('storageKey');
/* $scope.$watch("storageKey", function() {debugger;
localStorage.setItem('storageKey', storageKey);
});*/
function submit() {
if($rootScope.name!=null) {
var JSONObject = {
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email,
"review":$rootScope.review
}
var temp={
"name":$rootScope.name,
"surname":$rootScope.surname,
"email":$rootScope.email
}
$scope.localArray.push(temp);
localStorageService.set("storageKey", $scope.localArray);
$scope.storageKey = localStorageService.get("storageKey");
// $rootScope.obtained_array = localStorageService.get("storageKey"); debugger;
console.log($scope.storageKey);debugger;
var Results = UniversalService.PostReview(JSON.stringify(JSONObject));
}
}
}
main.controller.js
'use strict';
var app= angular.module('app').controller('MainController', MainController);
MainController.$inject = ['$location', 'AuthenticationService', 'FlashService', 'UniversalService', '$scope', '$sce', '$rootScope','$log','PagerService','localStorageService','$mdDialog'];
function MainController($location, AuthenticationService, FlashService, UniversalService, $scope, $sce, $rootScope,$log,PagerService,localStorageService,$mdDialog) {
var vm = this;
vm.allreviews = [];
vm.allusers=[];
vm.allemails=[];
vm.all=[];
vm.avatars=[];
$scope.filteredAll = [];
$scope.all=[];
$scope.items=[];
$scope.pager = {};
$scope.setPage = setPage;
loadAllReviews();
loadAllEmails();
loadAllUsers();
loadAll();
loadAvatars();
initController();
setPage();
submit();
$scope.init = function () {
$scope.$parent.storageKey = localStorage.getItem("storageKey");debugger;
// $scope.obtained_array = localStorage.getItem("storageKey");
// console.log(obtained_array); debugger;
// $scope.storageKey = localStorage.getItem("storageKey");debugger;
};
function refresh() {
location.reload();debugger;
}
function loadAll() {
UniversalService.GetAll()
.then(function (a) {
$scope.all=a;
});
}
function loadAllUsers(callback) {
UniversalService.GetAll()
.then(function (response) {
$scope.users=response;
if (callback) {
callback(response);
}
});
}
function loadAllReviews() {
UniversalService.GetAllReviews()
.then(function (review) {
vm.allreviews = review;
});
}
function loadAllEmails() {
UniversalService.GetAllEmails()
.then(function (email) {
vm.allemails = email;
});
}
function setPage(page) {
loadAllUsers(function (response) {
if (response) {
if (page < 1 || page > $scope.pager.totalPages) {
return;
}
// get pager object from service
$scope.everything=response;
$scope.pager = PagerService.GetPager(response.length, page);
// get current page of items
$scope.items = response.slice($scope.pager.startIndex, $scope.pager.endIndex + 1);
}
});
}
function initController() {
$scope.setPage(1); // initialize to page 1
}
}
HTML file:
<div class="container padding-tb" id="Review">
<div ng-controller="ReviewController" ng-init="init()" ng-app id="Review">
<h2>Add review</h2>
<form name="form" ng-submit="vm.submit()" role="form">
<div >
<div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="text" ng-model="name" onchange="CallItems()" id="name" class="form-control" ng-model="vm.name" placeholder="Enter name here" required />
<span ng-show="form.name.$dirty && form.name.$error.required" class="help-block">Name is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="text" ng-model="surname" name="text" id="surname" class="form-control" ng-model="vm.surname" placeholder="Enter surname here" required/>
<span ng-show="form.surname.$dirty && form.surname.$error.required" class="help-block">Surname is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" id="email" class="form-control" ng-model="vm.email" placeholder="Enter email here" required />
<span ng-show="form.email.$dirty && form.email.$error.required" class="help-block">Email is required</span>
</div>
</div>
<div>
<div class="form-group">
<label for="review">Review</label>
<input type="text" name="text" id="review" class="form-control" ng-model="vm.review" placeholder="Enter review here" required/>
<span ng-show="form.review.$dirty && form.review.$error.required" class="help-block">Review is required</span>
</div>
</div>
<div class="form-actions">
<button id="submit" type="submit" onclick="passInfo()" class="btn btn-primary">Submit</button>
<label style="display:none" id="label"><font color="white">Review succesfully created!
<a onclick="refresh()" href="../ang/#!/review">Add new review</a></label> or
View reviews!
</div>
</div>
</form>
<div>
<div ng-init="init()" class="slide-animate-container">
<div class="slide-animate" ng-include="main.view.html"></div>
</div>
</div>
</div>
Currently I add these values to button to test if values are added:
<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>
My main.view is inserted into the review.view (because form and reviews are on the same page, main is for the review listing and reviews are submitted form)
After submiting form all these values appear in the button, but after refreshing page none of them are shown anymore. I kind of understand that it is all because everything I do with local storage is inside submit() function, but I am not sure how to fix it
You can write a init function on second controller and set the local Storage value in a variable.So whenever you refresh the page, init function will be called and local storage value will be available for you to use it in View
see below line:
<button ng-disabled="localStorage.getItem('LS_wimmtkey') !== null"> {{obtained_array}}</button>
"obtained_array" belong to $rootScope, so $rootScope can't bind to the template(binding to $rootScope is not possible )
quick solution is: change the following line
in case of: MainController
$scope.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;
in case of :ReviewController (you are setting in this ctrl "LS_wimmtkey")
$scope.$parent.obtained_array = localStorage.getItem("LS_wimmtkey");debugger;
This is my code.
$scope.sendFeedback = function () {
var mobile1 = $scope.mobile;
var feedback1 = $scope.feedback;
var userfeedback = {
mobile: mobile1,
feedback: feedback1
};
var feedbackRef = firebase.database().ref("feedback/");
var newFeedbackRef = feedbackRef.push();
newFeedbackRef.set(userfeedback, function(error) {
if (error) {
alert ('Error while registering feedback.');
} else {
$scope.feedback = '';
alert ('Your feedback is registered.');
}
});
}
After calling this function i can see alert ('Your feedback is registered.'); but $scope.feedback = '' not setting that particulat textField as empty. I tried $scope.feedback = null; also, but no luck.
what is wrong here?
Edit: HTML View added.
<md-input-container class="md-block">
<label>Feedback</label>
<input required="" name="feedback" ng-model="feedback" >
<div ng-messages="projectForm.feedback.$error" role="alert">
<div ng-message-exp="['required']">
This field is required.
</div> </div>
</md-input-container>
I encountered that kind of problem several times, and solved it using the following workaround :
angular.element(document.getElementById('doc'))
.scope().$apply( function() {
$scope.feedback=''
)}
I made that very minimal working example, for the sake of testing the SO's snippet runner, and mostly using your own code. Hope this helps.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script>
var module=angular.module('test',[]).controller('test', function($scope)
{
$scope.click = function() {
$scope.feedback = '';
alert ('Your feedback is registered.');
}
})
</script>
</head>
<body>
<div ng-app="test" ng-controller="test" id='feedback'>
<md-input-container class="md-block">
<label>Feedback</label>
<input required="" name="feedback" ng-model="feedback" >
<div ng-messages="projectForm.feedback.$error" role="alert">
<div ng-message-exp="['required']">
This field is required.
</div> </div>
<button ng-click='click();'>click?</button>
</md-input-container>
</div>
$scope.feedback = [];
(or)
setTimeout(function () {
$scope.$apply(function () {
$scope.feedback = [];
});
}, 1000);
Do you have ng-app and ng-controller set? I tested your code on my machine, and it works as long as you have the app and controller set up.
Can you make a JSFiddle?
I am using ng-init to get some default values in my input fields. Its working properly. But when I add ng-autocomplete to the input field the default value is no longer showing in input field.
index.html
<!DOCTYPE html>
<html ng-app=testApp>
<head>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
<script src="script.js"></script>
<script src="ngAutocomplete.js"></script>
</head>
<body>
<div ng-controller="searchCtrl" ng-init="roomsInit('london')">
<input type="text" ng-autocomplete ng-model="searchLocation" class="form-control input-lg" options="locationFilter">
</div>
</body>
</html>
script.js
app = angular.module("testApp", ['ngAutocomplete']);
app.controller('searchCtrl', function ($scope, $http) {
$scope.locationFilter = {
country: 'uk',
types: '(cities)'
}; $scope.details2 = '';
$scope.roomsInit = function (location) {
$scope.searchLocation = location;
//below code is not relevant to this case
$http({
url: "/search.json",
method: "GET",
params: {location: $scope.searchLocation,
q: {
daily_price_gteq: $scope.min_price,
daily_price_lteq: $scope.max_price,
room_type_eq_any: [$scope.private, $scope.entire, $scope.shared]
}
},
paramSerializer: '$httpParamSerializerJQLike'
}).success(function (response) {
$scope.rooms = response.rooms;
});
};
});
If I remove the ng-autocomplete it works fine.Could someone have a look
Here is the plunker
The directive you are using doesn't support ng-model and requires you to pass your model to ng-autocomplete:
<input type="text" ng-autocomplete="result" details="details" class="form-control input-lg" options="locationFilter">
This runs the auto-complete when you type in the box.
I believe the directive you are after is this one: https://github.com/wpalahnuk/ngAutocomplete/blob/master/src/ngAutocomplete.js
UPDATE
The directive you are using has a watch which clears the value after it runs the first time:
scope.$watch(scope.watchOptions, function () {
initOpts()
newAutocomplete()
element[0].value = ''; // <-- This resets the value
scope.ngAutocomplete = element.val();
}, true);
If you don't care about modifying the directive, change it to this:
scope.$watch(scope.watchOptions, function (newValue, oldValue) {
if (newValue !== oldValue) {
initOpts()
newAutocomplete()
element[0].value = '';
scope.ngAutocomplete = element.val();
}
}, true);
This stops it from wiping out the value unless you change the options/locationFilter.