I'm a beginner with AngularJS. However, I can't update $rootScope value after submit a form, it's being returned as undefined.
The Controller:
app.controller('campaignCtrl', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.submit = function() {
$rootScope.campaign = this.campaign;
};
}]);
And the form:
<form class="holder" name="campaignForm" ng-submit="submit()" >
<div class="form-group" show-errors>
<label for="inputDate">Date</label>
<p class="help-block"><em>Ex: 12/10/2015</em></p>
<input type="date" class="form-control" name="inputDate" ng-model="campaign.date" id="inputDate" required>
</div>
<button type="submit" class="btn btn-lg btn-default pull-right">Submit</button>
</form>
I used your code and added a $watch on $rootScope.campaign and it worked great.
.controller('someController', function($scope, $rootScope) {
$scope.submit = function() {
$rootScope.campaign = $scope.campaign;
};
$rootScope.$watch('campaign', function(newVal, oldVal) {
if(newVal !== oldVal) {
console.log("New Val = ");
console.log(newVal);
}
});
});
JSFiddle
If you are looking for something that persists across a page refresh, that is not $rootScope. Look at something like this: AngualrJS: sustaining data on html refresh
Check this. Your code seems correct except that you are missing closing tag on the input
`http://jsfiddle.net/ashishmusale/2001cf6r/`
Try
$scope.submit = function() {
$rootScope.campaign = $scope.campaign;
};
EDIT:
Try removing type="submit" from your button. It could be that your handler doesn't get called because the browser handles the form submission automatically (although you could verify that by putting a log in that function).
<button class="btn btn-lg btn-default pull-right">Submit</button>
EDIT 2:
Per our conversation via comments: $rootScope doesn't persist across requests. You'll need to store it somewhere permanent (like local storage or a cookie) or pass it to the server and then back to the client if you want to hold on to that value. I bet if you add a log inside that $scope.submit function, it will have a value there.
Related
I'm new to Angular, and I struggle with validating a multi select input with ngOptions attribute.
I want the field to be required, so the user must chose at least one option. However the validation methods Angular have simply doesn't work in my case, Here's what I've tried:
<form name="products" novalidate>
<div class="form-group">
<label for="select-product">Chose product/s</label>
<select id="select-product" name="selectedProduct" class="form-control"
required
multiple
ng-model="selectedProduct"
ng-options="product.name for product in products">
</select>
</div>
<button class="btn btn-primary pull-left" ng-click="products.selectedProduct.$valid && goToChildrenId()">Next</button>
</form>
Even if I chose a product and I can see that the form class switch from .ng-invalid to .ng-valid, the function goToChildrenId() doesn't run.
Also, if I add {{products.selectedProduct.$valid}} at the bottom, when I refresh the page I can see "false" for a second but it disappear, why?
If it's relevent, this is the controller:
adminCheckout.controller('productsCtrl', function($scope, $http, wpMiniapps, $location, $rootScope){
$scope.products = [];
var url = wpMiniapps.routeUrl("getProducts");
$http.post(url, {}).then(function(res){
$scope.products = res.data.data;
}, function(err){
console.log(err);
});
$scope.$watch('selectedProduct', function (newVal) {
$rootScope.globalData.products = newVal;
});
$scope.goToChildrenId = function(){
$location.path('/select-children');
};
});
I searched the web but nothing seems to work in my case.
I will really appreciate any help.
You have a variable name collision which is causing the problem: the form is named products and this ends up as a $scope variable. But it collides with $scope.products = [] from the controller. Simply renaming the form to, e.g., productsForm solves the problem:
<form name="productsForm" novalidate>
...
<button class="btn btn-primary pull-left" ng-click="productsForm.selectedProduct.$valid && goToChildrenId()">Next</button>
</form>
I've got a project in which you write a note in a formulary. Then, you submit that note into an information container (now it's just an array for testing purposes, but it's intended to be a DB later).
The formulary has the following controller:
app.controller('controlFormulario', ['$scope', 'SubmitService', function($scope, submitService) {
$scope.formData = {
"titulo":"",
"texto":"",
"fecha": new Date()
};
$scope.submit = function() {
var temp = $scope.formData;
submitService.prepForBroadcast(temp);
}
// more things we don't need now
... which is bound to this part of the DOM, which is added into it, via a directive:
<form ng-controller="controlFormulario as formCtrl">
<div class="element">
<div class="form-group" ng-class="{'has-error': formData.titulo.length > 50 }">
<label for="inputTitulo">Título</label>
<input type="titulo" class="form-control" id="inputTitulo" ng-model="formData.titulo">
<span ng-show="formData.titulo.length > 50" id="helpBlock" class="help-block">El título no puede exceder los 50 caracteres.</span>
</div>
<div class="form-group">
<label for="inputTexto">Texto</label>
<textarea class="form-control" id="inputTexto" ng-model="formData.texto"></textarea>
</div>
<div class="form-group">
<label for="fecha">Fecha</label>
<input type="fecha" class="form-control" id="fecha" ng-model="formData.fecha" disabled>
</div>
<div class="form-group" >
<button class="btn btn-primary" style="height:35px;width:100px;float:right;" id="submit"
ng-disabled="isDisabled()" ng-click="submit()">
Enviar
</button>
</div>
</div>
<div class="note" ng-show="formData.titulo.length > 0">
<div class="title" ng-model="formData.titulo" class="title">{{formData.titulo | limitTo:50}}</div>
<div class="text" ng-model="formData.texto" class="text">{{formData.texto}}</div>
<div class="date" ng-model="formData.fecha" class="date">{{formData.fecha | date}}</div>
</div>
</form>
This is my directive (I don't think it's really needed, but just in case):
app.directive('formulario', [function() {
return {
restrict: 'E', // C: class, E: element, M: comments, A: attributes
templateUrl: 'modules/formulario.html',
};
}]);
I use a service for passing the data between the previous controller, and the note controller (which controls the note objects of the array). This is the service:
app.factory('SubmitService', function($rootScope) {
var data = {};
data.prepForBroadcast = function(recvData) {
data.data = recvData;
this.broadcastItem();
};
data.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return data;
});
... and I receive it in this part of my note controller:
app.controller('noteController', ['$scope', 'SubmitService', function($scope, submitService) {
var nc = this;
$scope.$on('handleBroadcast', function() {
nc.pruebaNota.push(submitService.data);
$scope.formData.titulo = "";
$scope.formData.texto= "";
$scope.formData.fecha = new Date();
});
// more things, the array, etc...
Ok. This should work, and it does, but something strange happens: as you can see, the preview note is binded with ng-model to the form. That works great, ok. But when I submit the form, the new note object keeps bound to the form (so if I delete the form text, the note appears in blank, and if I write something, it gets automatically updated both in the preview note, and the new note), when there isn't any relation between them. The new note, which appears dynamically on the screen, shouldn't be bound to anything.
Am I doing something wrong? Some help would be really nice!
You are forgetting something really important. Memory address. So, the rought idea is something like: imagine that $scope.formData is in the address 123123. You first create a temp var pointing to 123123 then you send it to the service and the service holds the same address 123123 into data.data.
Then in your second controller you say: hey, I want to work with that data.data (AKA your data in 123123) you have SubmitService.
Now when you modify $scope.formData again, you are updating what you have in that 123123 and everything that is "looking" into that address will be updated.
That is the rough idea. To point it simple, you're modifying the same piece of information everywhere.
See it here: http://plnkr.co/edit/zcEDQLHFWxYg4D7FqlmP?p=preview
As a AWolf suggested, to fix this issue, you can use angular.copy like this:
nc.pruebaNota.push(angular.copy(submitService.data));
I'm having difficulty figuring this out. I have a directive building html from promise data. For each row, it's adding buttons for CRUD operations. I do not know how to get the button event to trigger in my controller. Regardless of how my controller is set up, how can I get the event to register in my controller? I am currently trying $emit, but nothing seems to happen.
Directive generated html:
controls = controls+'<button type="button" data-tooltip-placement="bottom" data-tooltip="'+action.name+'" ng-click="$emit(''+action.broadcaster+'','+rowId+')" name="'+action.name+'" class="btn btn-xs btn-default ng-scope"><i class="'+action.icon+'"></i> </button>'
How it looks in Chrome tools:
<button type="button" data-tooltip-placement="bottom" data-tooltip="delete" ng-click="$emit('removeOrgCourse',134)" name="delete" class="btn btn-xs btn-default ng-scope"><i class="fa fa-trash-o"></i> </button>
and my controller listener:
$scope.$on('removeOrgCourse', function( event, data ){
console.log(data);
});
UPDATE:
Just changed the ng-click to console.log("click") and nothing happened. So the issue is that ng-click is not registering;
While you can use events in angular to achive that, one other option is to use & expression scope binding to pass controller method to directive. Example code (from egghead.io)(see working code at jsbin):
<div ng-app="phoneApp">
<!-- we've replaced the use of $scope with the preferred "controller as" syntax. see:http://toddmotto.com/digging-into-angulars-controller-as-syntax/ -->
<div ng-controller="AppCtrl as appctrl">
<div phone dial="appctrl.callHome(message)"></div>
<div phone dial="appctrl.callHome(message)"></div>
<div phone dial="appctrl.callHome(message)"></div>
</div>
Controller:
app.controller("AppCtrl", function() {
var appctrl = this;
appctrl.callHome = function(message) {
alert(message);
};
});
And directive:
app.directive("phone", function() {
return {
scope: {
dial: "&"
},
template: '<input type="text" ng-model="value">' +
'<div class="button" ng-click="dial({message:value})">Call home!</div>'
};
});
Maybe you have to use $broadcast, depends if the controllers are on the same level or who's over who.
Working with $scope.$emit and $scope.$on
http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
in the secon link you can put the $emit and $broadcast in the same controller and see whad do you catch in you $on
I'm opening a $modalInstance in which user has to choose an option from radio inputs (values loaded dynamically) and return chosen value.
I have this function to open the $modalInstance:
$scope.openAddFriendGroup = function () {
var addFriendGroupModal = $modal.open({
templateUrl: "addFriendGroupModal.html",
controller: ModalAddFriendGroupCtrl,
resolve: {
myDetails: function () {
return $scope.info;
}
}
});
};
Then this is the $modalInstance controller:
var ModalAddFriendGroupCtrl = function ($scope, $modalInstance, myDetails, groupsSvc) {
$scope.addableFriends = [];
$scope.chosenFriend = null;
//here goes a function to retrieve value of $scope.addableFriends upon $modalInstance load
$scope.addFriend = function () {
$scope.recording = true;
groupsSvc.addFriend($scope.chosenFriend, myDetails).then(function (response) {
if(response.status && response.status == 200) {
$modalInstance.close($scope.userid);
}
}, function (err) {
$modalInstance.dismiss(err);
});
};
};
And this is addFriendGroupModal.html, the HTML for the modal itself:
<div id="add-friend-group-modal">
<div class="modal-header">
<h3 class="modal-title">Add friend</h3>
</div>
<div class="modal-body">
<form class="form" role="form" ng-hide="loading">
<div class="form-group">
<label class="control-label">Friend:</label>
<div class="radio" ng-repeat="thisFriend in addableFriends">
<label>
<input type="radio" id="friend{{thisFriend.id}}" name="chosenFriend" ng-model="$parent.chosenFriend" ng-value="thisFriend" /> {{thisFriend.name}} {{thisFriend.surname}}
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="addFriend()">Add friend</button>
</div>
</div>
Now, the problem comes when I try to retrieve the value that has been selected in the radio buttons of the form in the modal. I can't seem to retrieve this value in $scope.addFriend. The value of $scope.chosenFriend stays at null and does not get updated when selecting a radio option.
What am I doing wrong?
$modal.open returns promise so try :
var addFriendGroupModal;
$modal.open({ ...})
.result.then(function(response){
addFriendGroupModal = response;
});
<input type="radio" id="friend{{thisFriend.id}}" name="chosenFriend" ng-model="$parent.chosenFriend" ng-value="thisFriend" /> {{thisFriend.name}} {{thisFriend.surname}}
in here your ng-model is $parent.chosenFriend so, why are you expecting $scope.chosenFriend to not be a null? change you ng-model property to $scope.chosenFriend.
Retrieved answer from a related question, by gertas
Angular-UI modals are using transclusion to attach modal content, which means any new scope entries made within modal are created in child scope. This happens with form directive.
This is known issue: https://github.com/angular-ui/bootstrap/issues/969
I proposed the quick workaround which works for me, with Angular 1.2.16:
<form name="$parent.userForm">
The userForm is created and available in modal's controller $scope. Thanks to scope inheritance userForm access stays untouched in the markup.
<div ng-class="{'has-error': userForm.email.$invalid}"}>
So, in my form I would have to set a name="$parent.friendForm" attribute to <form>, and then bind the radio button model to it, ng-model="friendForm.chosenFriend" to be able to read it from the modal scope at $scope.friendForm.chosenFriend.
I have a form and I want to catch it submission, check validation of data and than submit form to the action inside the HTML form.
<div ng-controller="contactCtrl">
<form action="someAction" method="post" name="contactForm" class="clearfix frmContact">
<div class="one_half">
<input id="txtName" ng-model="name" value="" class="form-control">
</div>
<button ng_click="save($event)" type="submit">Send Message</button>
</form>
</div>
and my js:
var app = angular.module('bloompyApp', []);
app.controller("contactCtrl", function($scope, $http) {
$scope.email = "";
$scope.name = "";
$scope.message = "";
$scope.left = function() {return 100 - $scope.message.length;};
$scope.clear = function() {$scope.message = "";};
$scope.save = function(ev) {
ev.preventDefault();
console.log(angular.element(document.querySelector('body')));
if ($scope.contactForm.$valid) {
$http.get("/posts/")
.success(function(response) {console.log(response);});
}
};
});
You should:
Use the ng-submit directive on your form
Pass the form element to your save() method
Use the $http service to post
var ctrl = function ($scope, $http, $log) {
$scope.save = function (form) {
//if (!$scope.contactForm.$valid) return;
var url = form.attributes["target"];
$log.debug(url);
$http
.post(url, { email: $scope.email, name: $scope.name })
.success(function (response) {
$log.debug(response);
})
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<form ng-submit="save($element.action)">
<button type="submit">Send Message</button>
</form>
</div>
I really advice you to follow this page of the docs from the beginning to the end, you'll change your approach to form using AngularJS :)
https://docs.angularjs.org/guide/forms
Use ng-submit instead on the form element
"Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page), but only if the form does not contain action, data-action, or x-action attributes."
It will also only run the expressions if the native html5 validation is valid