re enabling ng-disabled button in Angular JS - javascript

I am a newbie to AngularJS. I have created a form with fields which is disabled using ng-disabled by default. when I click on the edit <button> I want these fields to re-enable.
HTML
<form class="form-horizontal" role="form" ng-submit="edit_setting()" ng-controller="ExchangeController">
<div class="form-group">
<label>Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.name" ng-disabled="true">
</div>
</div>
<div class="form-group">
<label>Host Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.host_name" required ng-disabled="true">
</div>
</div>
<div class="form-group">
<label>Address</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.address" ng-disabled="true">
</div>
</div>
</form>
Controller
function ExchangeController($scope, $http, $cookieStore, $location) {
var edit_exchange_setting = "https://pvbp.com/api/settings.html?contactid=292351&exchange_id=7124&clearinghouseid=1&token=e5349652507c0esae86d50fdbdc53222cf97&page=view";
$http.get(edit_exchange_setting).success(function(response){
$scope.exchange_dt.exchange_name = response.name;
$scope.exchange_dt.exchange_host_name = response.host_name;
$scope.exchange_dt.exchange_last_processed_date = response.address;
});
$scope.edit_exchange_setting_click = (function(){
// how can i make the fields re enable here
});
}

in controller create scope variable,
$scope.disabled= true;
and replace all ng-disabled with that variable like,
...ng-model="exchange_dt.name" ng-disabled="disabled"....
when you click on edit button set $scope.disabled to false like,
$scope.edit_exchange_setting_click = (function(){
$scope.disabled = false;
});

you can have a scope variable keeping the true or false value.and a setter for that variable.
function ExchangeController($scope, $http, $cookieStore, $location) {
var edit_exchange_setting = "https://pvbp.com/api/settings.html?contactid=292351&exchange_id=7124&clearinghouseid=1&token=e5349652507c0esae86d50fdbdc53222cf97&page=view";
$http.get(edit_exchange_setting).success(function(response){
$scope.exchange_dt.exchange_name = response.name;
$scope.exchange_dt.exchange_host_name = response.host_name;
$scope.exchange_dt.exchange_last_processed_date = response.address;
});
$scope.edit_exchange_setting_click = (function(){
// how can i make the fields re enable here
});
$scope.dtName=true;
$scope.isdtNameDisabled=function()
{
return $scope.dtName;
};
$scope.updatedtName=function(flag)
{
$scope.dtName=flag;
};
}
and in your HTML you can bind that getter function.
<div class="form-group">
<label>Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.name" ng-disabled="isdtNameDisabled()>
</div>
</div>

You need to create a variable at the top of controller say
$scope.mydisabled=true;
then set your ng-disable with the variable
ng-disabled="mydisabled"
and on click of edit button set its value to false
$scope.mydisabled=false;
UPDATE
Fiddle

A different (however similar) approach is to wrap your form contents in a fieldset and have ng-disabled in the fieldset only rather than in all the input fields. To make the html more cleaner.
<form class="form-horizontal" role="form" ng-submit="edit_setting()" ng-controller="ExchangeController">
<fieldset ng-disabled ="isFormSetForSaving">
<div class="form-group">
<label>Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.name">
</div>
</div>
<div class="form-group">
<label>Host Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.host_name" required>
</div>
</div>
<div class="form-group">
<label>Address</label>
<div class="col-sm-6">
<input type="text" class="form-control" ng-model="exchange_dt.address">
</div>
</div>
</fieldset>
</form>
and now in the controller set the isFormSetForSaving to true/false as per your logic.
function ExchangeController($scope, $http, $cookieStore, $location) {
$scope.isFormSetForSaving = true;
var edit_exchange_setting = "https://pvbp.com/api/settings.html?contactid=292351&exchange_id=7124&clearinghouseid=1&token=e5349652507c0esae86d50fdbdc53222cf97&page=view";
$http.get(edit_exchange_setting).success(function(response){
$scope.exchange_dt.exchange_name = response.name;
$scope.exchange_dt.exchange_host_name = response.host_name;
$scope.exchange_dt.exchange_last_processed_date = response.address;
});
$scope.edit_exchange_setting_click = (function(){
// how can i make the fields re enable here
$scope.isFormSetForSaving = false;
});
}

Related

AngularJS 1.6.8: Unable to submit form and display success message

I have a simple query submission form with name, email and query fields and a component with a controller function having the submit function to submit the form.
I am using ng-submit directive in the <form></form> tag to submit the user input and display a success message on submission.
below is the code for the respective files.
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div>
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService,$rootScope) {
var vm = this;
$scope.navigate = function(home){
$state.go(home)
};
$scope.saveform = function(){
$scope.name= vm.name;
$scope.email= vm.email;
$scope.query= vm.email;
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted."
};
$scope.user = userService;
};
//localStorage code
function userService($rootScope) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
UPDATE: On Submit, When I check the response in network tab in dev tools, I do not see the submitted values. All I see is the markup.
In your template, the name of the method is saveform:
ng-submit="saveform()"
But in your controller, it's save:
$scope.save = function() { ... }
Rename it to saveform:
$scope.saveform = function() { ... }

Angular - $scope.myForm.$setPristine() is undefined

Form is not cleared after saved record in angularJs. I'm trying to reset form many ways, but form is not reset.
My angularjs version is 1.4.8.
This question is also a duplicate, but I tried what stack overflow users said. That has not worked for me.
Looking for a positive reply
Thank you.
Html code:
<form name="myForm" id="myForm" novalidate>
<input type="hidden" name="forumValue" ng-model="fid.forumValue"
id="forumValue" placeholder="fourm Id" />
<div class="form-group row">
<label for="inputAnswer" class="col-sm-2 col-form-label">Answer</label>
<div class="col-sm-10">
<textarea rows="10" name="answer" class="form-control"
ng-model="fid.answer" required></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<button type="button" class="btn btn-success"
ng-click="saveUserAnswer(fid)">Post Your Answer</button>
</div>
</div>
</form>
Controller Code:
$scope.saveUserAnswer = function(fid) {
UserRepository.saveUserAnswer(fid).then(
function(response) {
var status = response.message;
if (status == "success") {
alert("posted success");
$scope.UserAnswer=getUserOnIdAnswer(fid.UserValue);
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$state.go('UserAnswer');
}
else {
$scope.User=response;
alert("posted Fail,Please correct the details..!!");
}
});
};
Is your form wrapped in an ng-if statement? If so, the form might be inside a child scope, and you might try:
Option A
Replace your ng-if with an ng-hide.
Option B
Bind the form to an existing object on the parent scope:
$scope.myData = {};
$scope.saveUserAnswer = function(fid) {
...
};
Then in your HTML, refer to the form on the parent scope:
<form name="myData.myForm" id="myForm" novalidate>
</form>
Source: https://github.com/angular/angular.js/issues/15615
I have attempted to recreate your problem but without the call to the UserRepository just to confirm that we can set the form $pristine value to true and to reset the form.
<form name="form.myForm" id="myForm" novalidate>
<input type="hidden" name="forumValue" ng-model="fid.forumValue" id="forumValue" placeholder="fourm Id" />
<div class="form-grou`enter code here`p row">
<label for="inputAnswer" class="col-sm-2 col-form-label">Answer</label>
<div class="col-sm-10">
<textarea rows="10" name="form.myForm.answer" class="form-control" ng-model="fid.answer" required></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-2"></div>
<div class="col-sm-8">
<button type="button" class="btn btn-success" ng-click="saveUserAnswer(fid)">Post Your Answer</button>
</div>
</div>
</form>
<pre>{{form.myForm.$pristine}}</pre>
and the controller code like so :
$scope.form = {};
$scope.saveUserAnswer = function(fid) {
$scope.form.myForm.$setPristine();
$scope.fid = {};
//omitted the user repository code
};
The above will set the pristine value of the form to true and also reset the value of fid on click of the button.
EDIT
Also the call to your repository function should be in this format:
UserRepository.saveUserAnswer(fid).then(
function(response){
//success
},
function(response){
//error
}
);
In controller try to add '$scope.fid.answer=null;' after scope.myForm.$setPristine();
like this.
$scope.saveUserAnswer = function(fid) {
UserRepository.saveUserAnswer(fid).then(
function(response) {
var status = response.message;
if (status == "success") {
alert("posted success");
$scope.UserAnswer=getUserOnIdAnswer(fid.UserValue);
$scope.myForm.$setPristine();
$scope.myForm.$setUntouched();
$scope.fid.answer=null;
$state.go('UserAnswer');
}
else {
$scope.User=response;
alert("posted Fail,Please correct the details..!!");
}
});
};

angularjs how to access mulitple input fields from a form inside controller

How do I access the individual input names defined in a form inside my controller?
rates.rateName
rates.rateBitrate
rates.rateWidth
rates.rateHeight
This does not work: var url = {{ tmp + data.rateName }};
I need to extract one of the input values from the form and append it to the url
to be used with a $http POST. I need to put the rest of the inputs from the form (all together) into the POST as well as json blob.
<div ng-controller="RateCtrlAdd">
<rd-widget>
<rd-widget-header icon="fa-users" title="Rates">
</rd-widget-header>
</rd-widget>
<p></p>
<div class="row">
<div class="col-sm-6">
<form name="myForm" ng-submit="SendData()">
<input class="form-control input-lg" type="text"
placeholder="rate name"
name="rates.rateName"
ng-model="rates.rateName" required/>
<br>
<input class="form-control input-lg" type="text"
placeholder="rate bit rate"
name="rates.rateBitrate"
ng-model="rates.rateBitrate" required/>
<br>
<input class="form-control input-lg" type="text"
placeholder="rate width"
name="rates.rateWidth"
ng-model="rates.rateWidth" required/>
<br>
<input class="form-control input-lg" type="text"
placeholder="rate height"
name="rates.rateHeight"
ng-model="rates.rateHeight" required/>
</form>
</div>
</div>
<div class="row" style="margin-top: 12px;">
<div class="col-sm-6">
<button class="btn btn-success btn" value="Send" ng-click="SendData()">
Add
</button>
<a href="/rates" class="btn btn-danger btn">
Cancel
</a>
</div>
</div>
</div>
'use strict';
angular.module('RDash')
.controller('RateCtrlAdd', ['$scope', '$http', function($scope, $http) {
console.log('RateCtrlAdd - enter...');
$scope.SendData = function () {
var data = $scope.rates;
console.log('RateCtrlAdd - rates from input form: ', $scope.rates);
var tmp = 'http://10.10.15.145:8085/lms/outputstream/';
var url = {{ tmp + data.rateName }};
console.log('RateCtrlAdd - url: ', url);
}; // end function()
console.log('RateCtrlAdd - ...exit');
}]); // end controller()
You cant use binding expression i.e. {{}} in controller. Add it using simple javascript
Try this
var url = tmp + data.rateName;

scope values are not getting display in the view

I am new to AngularJS. I stored the response data in the scope in my controller . But the values stored in scope not getting displayed in the html page.
guest-controller.js
var guestProfileApp = angular.module('guestProfileApp', ['guestProfileServices' ]);
guestProfileApp.controller( 'guestProfileController', [ '$scope', 'guestProfileService', GuestProfileController ]);
function GuestProfileController( $scope, guestProfileService)
{
$scope.getProfile = getProfile;
$scope.saveProfile = saveProfile;
console.log('guest profile controller called');
function getProfile( profileID ){
return guestProfileService.getProfile( profileID ).then( function( response ){
$scope.profileBizObj = response.data;
console.log($scope.profileBizObj);
window.location = "profile.html";
});
}
}
profile.html
<html lang="en" ng-app="guestProfileApp">
<body ng-controller="guestProfileController">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="First Name" id="f_firstName" ng-model="profileBizObj.profileData.nameInfo.firstName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Last Name" id="f_lastName" ng-model="profileBizObj.profileData.nameInfo.lastName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="date" class="form-control" placeholder="Date of Birth" id="f_dob" ng-model="profileBizObj.profileData.nameInfo.birthDate">
<div class="input-group-addon"><span class="glyphicon glyphicon-gift"></span></div>
</div>
</div>
</body>
</html>
When I displayed the response data using
console.log($scope.profileBizObj);
The data is displaying correctly. But when I am moving to "profile.html" and trying to display the profileBizObj data using ng-model the values are not getting displayed.
Here is the output of console.log($scope.profileBizObj);
{"addressList":[],
"customerID":"MYCUST",
"emailList":[],
"formattedName":"JOHN PAWLIW, #388569330",
"phoneList":[],
"profileData":{"createdOn":"2015-11-24T14:05:58",
"customerID":"MYCUST",
"nameInfo":{"createdOn":"2015-11-24T14:05:58",
"firstName":"JOHN",
"lastName":"JOHN PAWLIW",
"mergedObjectState":2,
"middleName":"",
"nameInfoID":12642,
"nameTitle":"MR",
"profileID":7183,
"selectedLocale":"en_US",
"updatedOn":"2015-11-24T14:05:58"},
"profileID":7183,
"selectedLocale":"en_US",
"status":"ACTIVE",
"updatedOn":"2015-11-24T14:05:58"},
"profileID":7183,
}
Please help me as how to resolve this issue . Thank You
In order to display the $scope.profileBizObj in view.html. You can use ng-repeatto iterate through object properties.
<div ng-repeat="item in profileBizObj">
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="First Name" id="f_firstName" ng-model="item.profileData.nameInfo.firstName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="Last Name" id="f_lastName" ng-model="item.profileData.nameInfo.lastName">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
</div>
</div>
</div>
This is the fiddle link: https://jsfiddle.net/rrwfu834/2/
window.location = "profile.html"
loads a new page. The new page shares no information with the previous page. It's like hitting reload or typing a new url into the browser window.
Looking at your code, simply try removing that line to see if resolves your issue.
There are several ways to load a template within the current page - the easiest of which is probably ng-include.
You can also use routes or ui.router.
The issue is resolved by making following changes
profiletest.html
<body>
<div ng-app="guestProfileApp">
<div ng-controller="guestProfileController">
<button ng-click="getProfile(1546)">Show Profile</button>
<ng-include ng-if="showProfile" src="'profile1.html'"></ng-include>
</div>
</div>
</body>
guest-controller.js
function GuestProfileController( $scope, guestProfileService)
{
$scope.getProfile = getProfile;
$scope.saveProfile = saveProfile;
console.log('guest profile controller called');
function getProfile( profileID ){
return guestProfileService.getProfile( profileID ).then( function( response ){
$scope.showProfile = true;
$scope.profileBizObj = response.data;
});
}
}

ng-submit won't call function inside directive controller

ok, i think the question says it all, but just to be clear, i have the following form (I know it's long... I'm using bootstrap... and jquery):
<form class="form-horizontal" role="form" ng-submit="cal.addEvent()"novalidate>
<div class="form-group">
<label class="control-label col-sm-2" for="title">Title:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="title" placeholder="Event Title" ng-model="cal.newEvent.title">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="desc">Description:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="desc" placeholder="Event Description" ng-model="cal.newEvent.description">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="stime">Start Time:</label>
<div class="col-sm-8">
<input type="time" class="form-control" id="stime" ng-model="cal.newEvent.start">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="etime">End Time:</label>
<div class="col-sm-8">
<input type="time" class="form-control" id="etime" ng-model="cal.newEvent.end">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="submit" class="btn btn-success btn-block" data-role="none">Add Event</button>
</div>
</div>
</form>
this form is inside a directive which looks like this:
app.directive("calendar", function($http) {
return {
restrict: "E",
templateUrl: "templates/calendar.html",
scope: true,
transclude:true,
link: function(scope) {
//there's a bunch of code here that I don't believe has anything to do with ng-submit so i left it out
},
controller: ["$scope", "$rootScope", function($scope, $rootScope){
this.newEvent = {};
this.removeEvent = function(index){
$http.post("classes/main.php", {"fn": "calendarDel", "id": $scope.chosen[index].id}).success(function(data){
$scope.getEvents($scope.chosen[index].date);
});
}
this.addEvent = function(){
//this.newEvent.date = $scope.dateString;
console.log("AddEvent");
console.log(this.newEvent);
}
$scope.getEvents = function(date){
$http.post("classes/main.php", {"fn": "calendar", "id": $rootScope.user.id, "data": date}).success(function(data){
if(!data.Error){
$scope.chosen = data;
}
});
}
}],
controllerAs: 'cal'
};
});
the problem is that when i try to submit my form, i see no indication that the function has been called... i expect to at least see console.log("AddEvent");
does anybody see what may be causing this problem here?
FYI
the form is in a bootstrap 3 modal div, which is inside the same directive it's called from --- if you need to see the "bigger picture", so to speak, just ask :)
i have tried this.addEvent(), $scope.addEvent(), $rootScope.addEvent() no change
You should just be calling addEvent()
<form class="form-horizontal" role="form" ng-submit="addEvent()" novalidate>
and bind the function to your scope like
$scope.addEvent = function() {
From the angular docs on expresssions
expressions are evaluated against a scope object
so you should not write the expression as ng-submit="$scope.addEvent()" etc
You should add bindToController: true to the directive and specify scope: {} to create an isolate scope.
When an isolate scope is used for a component (see above), and controllerAs is used, bindToController: true will allow a component to have its properties bound to the controller, rather than to scope. When the controller is instantiated, the initial values of the isolate scope bindings are already available.
Reference: $compile

Categories