AngularJS: Get value from childController to parentController - angularjs

I can not get a value in my form, I have 2 controllers and I'm trying to print the value of a dropdownlist which is inside a second controller (CtrlB). How can I get the value from this child controller on my parent controller? Everything is working very good, the render with the values of my dropdownlist, my form, my validations, except the value that get the $scope.dropdownlist. Any help?
my CtrlA controller
$scope.register = function (isValid) {
name = $scope.name; // works!
documentType = $scope.dropdownlist; // Got undefined :(
}
my directive
<select ng-model="dropdownlist" <!-- I can not get this value inside my CtrlA controller-->
ng-options="x.description for x in types">
</select>
my form
<form role="form"
name="nonClientRegisterForm"
ng-submit="register(nonClientRegisterForm.$valid);"
novalidate>
<div class="form-group"
ng-class="{ 'has-error' : nonClientRegisterForm.name.$invalid && !nonClientRegisterForm.name.$pristine }">
<input
type="text"
name="firstinput"
ng-model="firstinput"
class="form-control"
required />
</div>
<div>
<!-- This component has its own controller that fills this dropdownlist -->
<dropdownlist ng-controller="CtrlB"></dropdownlist>
</div>
<span ng-show="
(nonClientRegisterForm.name.$invalid &&
!nonClientRegisterForm.name.$pristine)"
class="help-block">
Debes completar todos los campos.
</span>
<button
type="submit"
ng-disabled="nonClientRegisterForm.$invalid">
continuar
</button>
</div>
</form>
</div>

you should use $rootscope to get values from child controller to parent controller.
$scope.register = function (isValid) {
name = $scope.name;
documentType = $rootscope.dropdownlist;}
function CtrlB($scope) {
$rootscope.dropdownlist="A";}

Related

Issue with nested ng-controller in Angularjs

I am stuck with strange issue. Actually I am fetching the data from ajax and showing it on text boxes.
So, basically I have 3 text box (City, City1, City2). By default City textbox is visible rest will show if they have data from Ajax.
User can add city by clicking + button or remove by click on - button.
I am able to fetch and show the data properly on textboxes.
But when I want to add/show City1 or City by clicking on + button. It is simply executing form submit event.
Here is code for Ajax call.
formApp.controller('getprofile', function($scope,$http){
$http({
url: 'get_job_city.php',
method: "GET",
params: {uid: uid}
})
.success(function(data) {
if (data.success) {
$scope.formData.city1 = data.city1;
$scope.formData.city = data.city;
$scope.formData.city2 = data.city2;
}
});
})
Code for form save and show hide city textboxes.
var formApp = angular.module('formApp', []);
formApp.controller('formProfile1', function($scope,$http){
$scope.secondcity1city1 = false;
$scope.thirdcity2 = false;
$scope.hidecity1 = function() { $scope.secondcity1 = false; }
$scope.hidecity2 = function() { $scope.thirdcity2 = false; }
$scope.showcity = function() { $scope.secondcity1 = true; }
$scope.showcity1 = function() { $scope.thirdcity2 = true; }
$scope.formData = {};
$scope.formprofile1 = function() {
$scope.ajaxload = true;
var allData={'formData': $scope.formData, 'uid': uid}
$http({
method : 'POST',
url : 'city_update_exec.php',
data : allData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers
})
.success(function(data) {
$scope.ajaxload = false;
if (!data.success) {
$scope.errorcity = data.errors.city;
$scope.errorcity1 = data.errors.city1;
$scope.errorcity2 = data.errors.city2;
}else{
alert('City has been updated.');
}
});
};
})
HTML codes are below.
<div class="container" ng-controller="formProfile1">
<form name="formProfile1" method="post" id="formProfile1"
ng-submit="formprofile1()" role="form">
<div ng-controller ="getprofile">
<div id="firstcity">
<div class="col-xs-10">
<div class="topjob_resumetitle" ng-class="{ 'has-error' : errorcity }">
<input name="city" id="city" type="text"
class="form-control textbox1 txt-auto"
required="required" placeholder="Job Location* "
ng-model="formData.city">
<div class = "errorba" ng-show="errorcity">{{errorcity}}
</div>
</div>
</div>
<div class="col-xs-2">
<!--<button class="remove" ng-click="removeChoice()">-</button>-->
</div>
<button class="addfields" ng-click="showcity()">+</button><br>
</div>
<div ng-show="secondcity1">
<div class="col-xs-9"><div class="topjob_resumetitle" ng-class="{ 'has-error' : errorcity1 }">
<input name="city1" id="city1" type="text"
class="form-control textbox1 txt-auto"
placeholder="Job Location* " ng-model="formData.city1">
<div class = "errorba" ng-show="errorcity">{{errorcity1}}
</div>
</div>
</div>
<div class="col-xs-3">
<button class="remove" ng-click="hidecity1()">-</button>
<button class="addfields" ng-click="showcity1()">+</button><br>
</div>
</div>
<div ng-show="thirdcity2">
<div class="col-xs-10"><div class="topjob_resumetitle"
ng-class="{ 'has-error' : errorcity2 }">
<input name="city2" id="city2" type="text"
class="form-control textbox1 txt-auto"
placeholder="Job Location* "
ng-model="formData.city2">
<div class = "errorba" ng-show="errorcity2">{{errorcity2}}
</div>
</div>
</div>
<div class="col-xs-2">
<button class="remove" ng-click="hidecity2()">-</button>
</div>
More text boxes are here
</div>
The problem is that you have not set a type for your buttons, and therefore are defaulting to submit types, which will submit the first parent form found in the DOM when clicked. To allow your custom click handlers to execute properly, change your button types to "button" like so:
<button type="button" class="addfields" ng-click="showcity()">+</button><br>
Remove method="post" and add novalidate on form tag it will stop html5 validation
<form name="formProfile1" novalidate id="formProfile1"
ng-submit="formprofile1()" role="form">
Also if its still not works then change all your button to
<input type="button">//for rest of the buttons
<input type="submit">//for submit button
To make an http request you don't need to use the separate controller. Use factory method in your code for ajax and inject it as a dependency in your controller. Refer Angular Factory method

form validation using angularjs

Im trying to validate my form, if the fields are valid then it should post the data to the DB if not prevent from posting the data to DB. when I submit the form Im getting an error TypeError: Cannot read property '$valid' of undefined, I don't know how to overcome it, need help in this.
html:
<form name="formvalidation">
<ion-view ng-controller="ValidationCheck">
<ion-content>
<div>
<strong>User:</strong> <br/>
<input ng-model="name" type="text" name="name" required/>
<ng-messages for="formvalidation.name.$error" ng-if="formvalidation.name.$invalid">
<div ng-messages-include="error/validation.html"></div>
<ng-messages>
</div>
</from>
<button ng-click="check()">
controller:
myApp.controller('ValidationCheck',function($scope, applicationService)
{
$scope.check=function(formvalidation){
var name={'name'=$scope.name};
$scope.submitted=true;
if(formvalidation.$valid){
applicationService.save(name,$scope.home);
}}});
Just change your if condition formvalidation.$valid to formvalidation
. because you already pass formvalidation.$valid in your function via ng-click
if(formvalidation){
...
...
...
}
Remove ng-click and add a ng-submit:
<form name="formvalidation" ng-submit="check()" novalidate>
Try this : ( controller before form )
<ion-view ng-controller="ValidationCheck">
<form name="formvalidation">
In your html you have:
<button ng-click="check(formvalidation.$valid)">
which calls the check function with either a true or false value (a boolean), depending on whether or not the form is valid.
In your controller you have the check function with the following if-statement:
if(formvalidation.$valid)
but formvalidation is a boolean (true or false)
I recommend removing the argument from check and simply access the formvalidation properties from the $scope variable.
so the html becomes
<button ng-click="check()">
and the controller becomes
$scope.check=function(){
var name={'name'=$scope.name};
$scope.submitted=true;
if($scope.formvalidation.$valid) {
applicationService.save(name,$scope.home);
}
}
<form> should come after controller declaration
<div ng-app="app">
<ion-view ng-controller="ValidationCheck">
<form name="formvalidation">
<ion-content>
var app = angular.module("app", []);
app.controller('ValidationCheck', function($scope) {
$scope.check = function(formvalidationBoolean) {
alert(formvalidationBoolean);
var name = {
'name': $scope.name
};
$scope.submitted = true;
if (formvalidationBoolean) {
//applicationService.save(name, $scope.home);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<ion-view ng-controller="ValidationCheck">
<form name="formvalidation">
<ion-content>
<div>
<strong>User:</strong>
<br/>
<input ng-model="name" type="text" name="name" required/>
<ng-messages for="formvalidation.name.$error" ng-if="formvalidation.name.$invalid">
<div ng-messages-include="templates/admin/validation.html"></div>
<ng-messages>
</div>
</from>
<button ng-click="check(formvalidation.$valid)">Submit</button>
</div>
You are sending boolean value "ng-click="check(formvalidation.$valid)", So your statement if(formvalidation.$valid){ inside controller is wrong.
And You need to change "=" to ":" in var name = {'name': $scope.name };

posting data through angular form without page reload in angular

$scope.createPermission= function(form){
AppFactory.createNewPermission(form)
.success(function(data) {
$scope.updatedPermissions = data;
$scope.navMode='getPermission'
var original = $scope.permission;
$scope.reset(original);
$scope.permission = {}; // clear the form
})
.error(function(data) {
console.log('Error in creating permission: ' + data);
});
$scope.Execute=function(id) {
if($scope.navMode=='updatePermission') {
$scope.editPermission(id);
} else if($scope.navMode=='createPermission') {
$scope.createPermission($scope.permission);
}
}
}
$scope.reset= function(original) {
$scope.permission= angular.copy(original)
$scope.form2.$setPristine(true);
//$scope.form2.$setUntouched(true);
}
HTML:
<div class="row">
<div class="container col-sm-6 col-sm-offset-2"
ng-show="navMode == 'createPermission' || navMode=='updatePermission' || navMode=='getPermission'">
<div>
<h1>Permissions</h1>
</div>
</div>
<form class="form2" ng-show="showHide('Create')" ng-if=""name="form2" ng-submit="Execute(permissionId)" novalidate>
<div class="form-group" ng-class="{ 'has-success': form2.name.$valid && submitted, 'has-error': form2.name.$invalid && submitted }">
<label>Permission Name</label>
<input type="text" name="name" class="form-control" ng-model="permission.name" required/>
<p class="help-block" ng-show="form2.name.$error.required && submitted">
A permission name is required
</p>
</div>
<div class="row col-lg-offset-3">
<button class="btn btn-primary" ng-disabled="form2.$invalid" type="submit">Save</button>
</div>
</form>
</div>
I have above piece of code in controller and is executed on submission of the form. Now , It does work fine on page reload but I can not add data through form back to back. I need to reload teh page everytime to post new data through the form.
Why exactly is that ?
How do I fix this?
Without seeing the HTML part of this, I would guess you are using the action attribute of <form>. AngularJS provides ng-submit which allows you to set a handler for the submit event, without actually 'submitting' the form in the traditional sense. See https://docs.angularjs.org/api/ng/directive/ngSubmit.

Mutual effect of model variables

I have a simple GUI I would like to implement via pure AngularJS - there are two (or more) groups of checkboxes like here: http://jsbin.com/cemitubo/2/edit
Here is the code from the link below:
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<div class="group">
<input type="checkbox" ng-model="tag.aaa"/>
<input type="checkbox" ng-model="tag.ccc"/>
</div>
<div class="group">
<input type="checkbox" ng-model="tag.zzz"/>
</div>
{{tag}}
</div>
JS:
angular.module('myApp', [])
.controller('MyController', function($scope){
$scope.tag = {aaa: true};
});
Once A checkbox of one of the groups is checked all the checkboxes of the other groups should be unchecked (and the change obviously should be reflected in the model).
I tried to $watch the tag model variable and setting false to the variables of the other groups in $watch callback. The problem is that it fires the $watch callback each time tag is changed by $watch callback.
What is the proper AngularJS solution?
Thanks in advance!
Use ng-change instead $watch:
Something like:
$scope.changed = function(item, type){
console.log(item);
if((type == 'aaa' || type == 'ccc') ){
$scope.tag.zzz = !item;
}
else if(type == 'zzz'){
$scope.tag.aaa = !item;
$scope.tag.ccc = !item;
}
}
HTML
<div class="group">
<input type="checkbox" ng-model="tag.aaa" ng-change="changed(tag.aaa,'aaa')"/>
<input type="checkbox" ng-model="tag.ccc" ng-change="changed(tag.ccc,'ccc')"/>
</div>
<div class="group">
<input type="checkbox" ng-model="tag.zzz" ng-change="changed(tag.zzz, 'zzz')"/>
</div>
Demo JSBIN

Bind dynamic element creation to keypress with AngularJS

I am trying to append an element to the DOM from user text input using AngularJS.
The desired behaviour is:
User types string into input ng-model "newTask"
Presses enter key
Dynamic element is then appended to the DOM
The relevant section of HTML is as follows:
<div class="add-task">
<input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>
<div class="task-list">
<a class="task"><span class="text">{{ newTask }}</span></a>
</div>
Currently the HTML is instantly updated. How can I bind this event to only happen after enter keypress? The AngularJS UI is also loaded.
Many appreciations,
an AngularJS newbie
Try creating a temp value
Html:
<input type="text" placeholder="Type then press enter to create task" ng-model="tmpTask" ng-keypress="saveTask($event)" />
Your ng-model binds to a tmpTask property. Only when enter is pressed, save it back to newTask
JS:
app.controller('MainCtrl', function($scope) {
$scope.saveTask = function (event){
if (event.keyCode == 13){
$scope.newTask = $scope.tmpTask;
}
}
});
DEMO
html
<form ng-submit="createTask()">
<input type="text" ng-model="newTaskText" />
</form>
<div ng-repeat="task in tasks">{{ task.text }}</div>
controller
$scope.tasks = [];
$scope.createTask = function() {
$scope.tasks.push({
text: $scope.newTaskText
});
};
Since one of the other answers addresses the ng-keypress, I'll offer up the fact you don't need to use the ng-keypress event but can just watch the variable instead which negates the need for enter:
http://plnkr.co/edit/osFGRtpHG46bMyp15mc8?p=preview
app.controller('MainCtrl', function($scope) {
$scope.taskList = [];
$scope.$watch('newTask', function(newVal){
if (newVal=="newTask") {
$scope.taskList.push("Task " + $scope.taskList.length);
$scope.newTask = null;
}
});
});
<body ng-controller="MainCtrl">
<div class="add-task">
<input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>
{{taskList.length}}
<div class="task-list" >
<a class="task" ng-repeat="task in taskList" ><span class="text">{{ task }} </span></a>
</div>
</body>

Resources