I have a simple form:
<form ng-submit='addMessage()'>
<input type='text' ng-model='chatMessage' placeholder='chat here' />
<input type='submit' value='chat' />
</form>
And at the moment, a very simple function:
$scope.addMessage = function() {
console.log($scope.chatMessage);
}
The console logging is just logging undefined, no matter what I type into the input box. Clearly I'm missing something, but I'm not sure what that is.
Depending on the way forms are used, sometimes $scope is out of context between the controller on the form. This is because addMessage(), and chatMessage are not on the same level of the $scope hierarchy.
One way to fix this is to create a container for your form items:
$scope.cont = {};
$scope.addMessage = function() {
console.log($scope.cont.chatMessage);
}
And in the form:
<input type="text" ng-model="cont.chatMessage" placeholder="chat here"/>
This is also something you should definitely read if you are going to use angular more: http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html
Look for that fiddle maybe you missed something different .
<div ng-app="app">
<div ng-controller="mainCtrl">
<form ng-submit='addMessage()'>
<input type='text' ng-model='chatMessage' placeholder='chat here' />
<input type='submit' value='chat' />
</form>
<pre>{{msg | json}}</pre>
</div>
</div>
JS:
var app = angular.module("app", []);
app.controller("mainCtrl", function ($scope) {
$scope.msg = [];
$scope.addMessage = function () {
$scope.msg.push($scope.chatMessage);
console.log($scope.chatMessage);
$scope.chatMessage = "";
}
});
This should work:
<form ng-submit='addMessage(chatMessage)'>
<input type='text' ng-model='chatMessage' placeholder='chat here' />
<input type='submit' value='chat' />
</form>
And in your controller:
$scope.addMessage = function(msg) {
console.log(msg);
}
UPDATE
based on your comments i think you are looking for something like this:
$scope.messages = [];
$scope.$watch('messages', function(newMessage) {
alert('hey, a message was added ! :' +newMessage);
}, true);
$scope.addMessage = function(msg) {
$scope.messages.push(msg);
};
Angular has so called watches, the watched function will trigger everytime when a new message is addded to the array. For more information about watches refer to the docs
Related
I have a form such as
Html:
<form ng-submit="log(user)">
<input type="text" ng-model="user.firstname">
<input type="text" ng-model="user.lastname
</form>
Angular:
.controller ('', function ($scope){
$scope.log = function (user){
console.log (user.firstname)
}
})
This was working before but now it throws cannot read property user.firstname
Please help me. Thank you
AngualarJs is rich in two way data binding. You didn't need to pass the scope object user in the function log. Its available in controller always with updated value. Just Initialise the user as scope object and try the code
In html:
<form ng-submit="log()">
<input type="text" ng-model="user.firstname" />
<input type="text" ng-model="user.lastname" />
</form>
In Js
.controller ('', function ($scope){
$scope.user = {}; // Declare here
$scope.log = function (){
console.log ($scope.user.firstname);
}
})
if user parameter is undefined you can't access firstname on undefined value, You can try below snippet to solve your problem.
.controller ('', function ($scope){
$scope.log = function (user){
if(user){ //Strict Check: toString.call(user) == "[object Object]"
console.log (user.firstname)
}
}
})
This is full working example, somewhat similar to yours.
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
Please try this.
Thanks
Amit
Remove below code
ng-submit="log(user)"
and remove button type submit
and add below line
<input type="button" ng-click="log()"/>
Your js file
$scope.log=function(){
console.log($scope.firstname);
console.log($scope.lastname);
}
I am bringing in some simple data via a service that uses angular-resource like so:
angular.module('InvoiceService',
['ngResource'])
.factory('InvoiceService', function ($resource) {
return $resource('data.json');
})
.controller("DashboardListCtrl", function (InvoiceService) {
var vm = this;
InvoiceService.query(function (data) {
vm.invoices = data;
});
vm.submit = function (form) {
console.log(form)
};
});
And the html:
<form name="invoices" role="form" novalidate>
<ul>
<li ng-repeat="invoice in vm.invoices">
<input type="checkbox" id="{{'id-' + $index}}" />
<p><strong>Order:</strong></p>
<p>{{invoice.order}}</p>
</li>
<input type="submit" value="Continue" ng-click="vm.submit(invoices)" />
</ul>
</form>
Everything works fine; the data is displays in the view as expected.
The question:
What I'd like to do is be able to select a checkbox, grab the bit of data associated with that checkbox, and pass it along to the next controller/view on submit. How can I do this?
So, what do I do next? Am I on the right track?
**EDIT: added all angular code to help clarify
Posting answer as reply too big to be useful.
You should be using $scope to isolate the controller's data from the rest of the page.
Read up about ng-model http://docs.angularjs.org/api/ng/directive/ngModel and how to use it to two-way-bind checkbox value to a controller variable. No need to use theFormName if you call $scope.submit = function() { } as your ng-model variable will be available in $scope already.
angular.module('InvoiceService',
['ngResource'])
.factory('InvoiceService', function ($resource) {
return $resource('data.json');
})
.controller("DashboardListCtrl", function ($scope, InvoiceService) {
InvoiceService.query(function (data) {
$scope.invoices = data;
});
$scope.submit = function () {
// FIXME to access a property of each $scope.invoices
console.log('checkbox1=' + $scope.invoices[0].checkbox1);
};
});
Then the HTML:
<form role="form" novalidate ng-controller="DashboardListCtrl"><!-- EDIT: added ng-controller=, remove name= -->
<ul>
<li ng-repeat="invoice in invoices"><!-- EDIT: remove 'vm.' -->
<input type="checkbox" id="{{'id-' + $index}}" ng-model="invoice.checkbox1" /><!-- EDIT: added ng-model= -->
<p><strong>Order:</strong></p>
<p>{{invoice.order}}</p>
</li>
<input type="submit" value="Continue" ng-click="submit()" /><!-- EDIT: remove 'vm.' -->
</ul>
</form>
I have a very simple script that contains angular js
<script>
var delightApp = angular.module('delightmeter', []);
delightApp.controller('delightController', function ($scope) {
$scope.delightScore = 0;
$scope.test = function () {
if (isNaN($scope.delightScore)) {
// do not bind if this happens
}
}
});
</script>
The html of the above script is
<div id="angularapp" data-ng-app="delightmeter" data-ng-controller="delightController">
<input id="Text1" type="text" data-ng-model="delightScore" />
{{delightScore}}
<input id="Button1" type="button" value="button" data-ng-click="test()"/>
</div>
As we know in angular two way binding happens whatever may be the value in $scope.delightScore it gets bound to the html page.
Is there any way to stop this binding from happening ?
Rather than binding to the variable directly, Bind to a function that does your check
<div id="angularapp" data-ng-app="delightmeter" data-ng-controller="delightController">
<input id="Text1" type="text" data-ng-model="delightScore" />
{{ValideDelightScore()}}
<input id="Button1" type="button" value="button" data-ng-click="test()"/>
</div>
And in your controller define:
$scope.ValideDelightScore = function () {
if (isNaN($scope.delightScore)) {
return "";
}else{
return $scope.delightScore
}
}
There is no way to do that because you are explicity binding the model in both scopes. And even if you could you should'n mess with the Angular life-cycle, or you are going to have a bad time.
The right way to achieve what you need is, or using solution purposed by #Shivas Jayaram, or use a filter in where you don't want to display the model if isNaN.
angular.module('myApp.filters', [])
.filter('NaNFilter', function($moment, $translate) {
return function(value) {
if(isNaN(val)) {
return '';
}
return value;
};
});
And in your template:
<div id="angularapp" data-ng-app="delightmeter" data-ng-controller="delightController">
<div>Show delightScore if !NaN: {{delightScore | NaNFilter}}</div>
<input id="Text1" type="text" data-ng-model="delightScore" />
{{delightScore}}
<input id="Button1" type="button" value="button" data-ng-click="test()"/>
</div>
I have a form like this -
<form name="myForm" novalidate>
There are some fields in the form which I am validating and then submitting the form like this -
<input type="button" ng-click="Save(data)" value="Save">
In the controller, I want to check if the form is not valid then Save() should show some error on the page. For that, I am setting up a watch like this -
$scope.$watch('myForm.$valid', function(validity) {
if(validity == false)
// show errors
});
But I am always getting this error on running it -
Cannot read property '$valid' of undefined
Can someone explain why?
Thanks
You just misspelled "myForm" in your controller code. In order to remove the error, Write "myform" instead of "myForm".
However I expect what you want is like this.
$scope.Save = function(data){
alert($scope.myform.$valid);
}
I setup jsfiddle.
In my case I was wrapping the form in a modal created in the controller and therefore got the same error. I fixed it with:
HTML
<form name="form.editAddress" ng-submit="save()">
<div class="form-group">
<label for="street">Street</label>
<input name="street" type="text" class="form-control" id="street" placeholder="Street..." ng-model="Address.Street" required ng-minlength="2" />
<div class="error" ng-show="form.editAddress.street.$invalid">
<!-- errors... -->
</div>
</div>
<button type="submit" class="btn btn-primary" >Save address</button>
</form>
JS
angular.module("app").controller("addressController", function ($scope, $uibModal, service) {
$scope.Address = {};
$scope.form = {};
$scope.save = function() {
if (modalInstance !== null) {
if (isValidForm()) {
modalInstance.close($scope.Address);
}
}
};
var isValidForm = function () {
return $scope.form.editAddress.$valid;
}
});
this is my solution, but I do not know if it is the right way.
html:
<div ng-controller='myctrl as mc'>
<form name='mc.form' ng-submit='mc.submit'>
<input type='email' name='email' />
<input type='user' name='user' />
<button type='submit'>submit</button>
</form>
</div>
javascript:
angular.module('myapp').controller('myctrl', ['$scope', function myctrl($scope) {
var th = this
this.submit = function(form) {
if(!th.form.$invalid) postToServer(getFormData())
}
//I checked the form object, no helper method like this
function getFormData() {
var res = {}
angular.forEach(th.form, function(value, key) {
if(key[0] !== '$') res[key] = value.$modelValue
})
return res
}
function postToServer(data) {
//do post to server
console.log(data)
}
}])
This is an example of basic Angular Forms usage. You want to use ng-modal and within your Controller $scope you should have a Object for your form data that you will be processing. If you give the form a name attribute, it will bind this to your Controller $scope so that you can access within your controller, for example <form name="myForm"> == $scope.myForm.
Please find this live example below, if you open your Console F12 menu you will see the form data when it is submitted.
http://plnkr.co/edit/XSiPnDdB5umxOzu0V3Pf?p=preview
<form name="myForm" ng-submit="submitForm()">
Email: <input name="email" type="email" ng-model="formData.email" />
<br />
User: <input name="user" type="text" ng-model="formData.user" />
<br />
<button type="submit">Submit</button>
</form>
<script>
angular.module('myApp', [])
.controller('mainCtrl', function($scope) {
$scope.formData = {};
$scope.submitForm = function() {
// do form submit logic
// this is the object declared in the controller
// binded with ng-model
console.log('$scope.formData');
console.log($scope.formData);
// this is the ng-form $scope binded into
// the Controller via <form name="name">
// this hold more that just the form data
// validation errors form example
console.log('$scope.myForm');
console.log($scope.myForm);
};
});
</script>
You should use ng-model, it will all the form data will be sent as an object
<div ng-controller='myctrl as mc'>
<form name='mc.form' ng-submit='mc.submit'>
<input ng-model='formData.email' name='email' />
<input ng-model='formData.user' name='user' />
<button type='submit'>submit</button>
</form>
</div>
The input value will bind to the properties of an object call formData in controller
angular.module('myapp').controller('myctrl', ['$scope',
function myctrl($scope) {
var th = this;
$scope.formData= {}; //Initialise the object
this.submit = function(form) {
if (!th.form.$invalid) postToServer();
}
function postToServer() {
//do post to server
console.log($scope.formData); //The value of input will bind to the property of formData
}
}
])