How to retrieve the value from textbox using AngularJs? - javascript

$scope.add=function()
{
//How to retrieve the value of textbox
}
<input type='text'><button ng-click='add()'></button>
When I click on the button, how can I retrieve the textbox value in the controller and add that value to the table dynamically?

Assign ng-model to it so that variable will be available inside scope of controller.
Markup
<input type='text' ng-model="myVar"/>
<button type="button" ng-click='add(myVar)'></button>

Bind the text field using ng-model
Example:
$scope.items = [];
$scope.newItem = {
title: ''
}
$scope.add = function(item) {
$scope.items.push(item);
$scope.newItem = { title: '' }; // set newItem to a new object to lose the reference
}
<input type='text' ng-model='newItem.title'><button ng-click='add(newItem)'>Add</button>
<ul>
<li ng-repeat='item in items'>{{ item.title }}</li>
</ul>

To take your data from textbox, you should use ng-model attribute on the HTML element. On the button element you can use ng-click with a parameter which is your ng-model
Example:
Your HTML:
<input type='text' ng-model="YourTextData"/>
<button type="button" ng-click='add(YourTextData)'></button>
Your Js:
$scope.add=function(YourTextData){
//Put a debugger in here then check the argument
}

Use ng-model in your textbox to bind them to your scope variables
<input type="text" ng-model="value1">
<input type="text" ng-model="value2">
Then declare the variables inside your controller and use them in your function
$scope.value1 = 0;
$scope.value2 = 0;
$scope.add=function()
{
// Example
console.log($scope.value1 + $scope.value2);
}

Related

Value in angular scope getting undefined

I have a scenario for deleting items.
For this, first I get a list of values with particular condition. The retrieved values whill be shown in the UI with radio buttons to choose the particular item to choose for deleting.
I have given the value for the radio buttons to be the id of the retrieved items. This id is used in angularJS method for deleting. Currently getting undefined value in the angular function inside the controller.
My angular controller is as below:
mainApp.controller("deleteToDoController", function($scope,$http) {
$scope.toDoList = {};
$scope.getToDo = function(){
var url = "http://localhost:8080/webservice-4.0/rest/todo/"+$scope.status;
$http.get(url)
.then(function(response) {
$scope.toDoList = angular.fromJson(response.data);
});
}
$scope.deleteToDo = function(){
var url = "http://localhost:8080/webservice-4.0/rest/todo/delete/"+$scope.deleteId;
$http.get(url)
.then(function(response) {
$scope.toDoList = angular.fromJson(response.data);
});
}
});
My html page code is :
<div ng-controller="deleteToDoController">
<form ng-submit="getToDo()">
ToDo Status:
<input type="radio" ng-model="status" value="completed"/>Completed<input type="radio" ng-model="status" value="pending"/>Not Completed
<input type="submit" value="View To Do"/><br>
<div ng-repeat = "toDo in toDoList">
<input type="radio" ng-model="deleteId" value="{{toDo.id}}"/>Task : {{toDo.name}}<br>
</div>
<input type="button" ng-click="deleteToDo()">Delete</button><br>
</form>
Appreciated!!!!
Since deletedId have been created inside ng-repeat child scope. You won't that scope variable outside ng-repeat, like you were trying to pass it in ng-click
You have to do following .
use Dot rule while defining model, so that Prototypal Inheritance will help to pass reference of variable to child scope.
Use ControllerAs pattern.
Html
<form ng-submit="getToDo()">
ToDo Status:
<input type="radio" ng-model="status" value="completed"/>Completed<input type="radio" ng-model="status" value="pending"/>Not Completed
<input type="submit" value="View To Do"/><br>
<div ng-repeat = "toDo in toDoList">
<input type="radio" ng-model="tobeDeleted.deleteId"
value="{{toDo.id}}"/>
Task : {{toDo.name}}<br>
</div>
<input type="button" ng-click="deleteToDo()">Delete</button><br>
</form>
Using Dot Rule
//define model
$scope.tobeDeleted = {}; //then place deleted property here
//you could easily access `$scope.tobeDeleted.deletedId` inside a controller
Your $scope.deleteId Will be undefiend. Your function should have a parameter deleteId,change the function as
$scope.deleteToDo = function(deletId){
var url = "http://localhost:8080/webservice-4.0/rest/todo/delete/"+ deleteId;
$http.get(url)
.then(function(response) {
$scope.toDoList = angular.fromJson(response.data);
});
}
make sure you pass Id Inside the html also,
<input type="button" ng-click="deleteToDo(toDo.id)">Delete</button><br>
EDIT
Since your delete button is outside ng-repeat You should use dot operator with ng-model for the deleteId
define a $scope variable as,
$scope.deleteItem = {};
and your HTML as,
<div ng-repeat = "toDo in toDoList">
<input type="radio" ng-model="deleteItem.deleteId" value="{{toDo.id}}"/>
</div>
<input type="button" ng-click="deleteToDo()">Delete</button><br>
and your controller as,
$scope.deleteToDo = function(){
var url = "http://localhost:8080/webservice-4.0/rest/todo/delete/"+$scope.deleteItem.deleteId;
$http.get(url)
.then(function(response) {
$scope.toDoList = angular.fromJson(response.data);
});
}

AngularJs ng-model substr

How can I set input value with without first letter of ng-model. I do not want to change model value itself. Just content of input to be without first letter.
<input type="text" ng-model="myVal" >
and js
$scope.myVal = 'Hello';
Wanted result: ello
Assuming you don't want two way data-bindin you can use value instead of ng-model
<input type="text" value="{{myVal.substr(1)}}" >
If you do want two way databinding, using substr on a model statement doesn't make sense.
Have 2 models and use ng-change in your input to update the original model as you change your input model.
angular.module('myApp',[]).filter('myFilter',function(){
return function(input){
input = input.substring(1,input.length);
return input;
};
})
.controller('myController',function($scope,$filter){
$scope.myValObj = "Hello";
$scope.myValObj2 = $filter('myFilter')($scope.myValObj);
$scope.updateOriginal = function(){
$scope.myValObj = $scope.myValObj[0] + $scope.myValObj2;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<input type="text" ng-model="myValObj2" ng-change="updateOriginal()"/>
<br>
Original Model: {{myValObj}}
<br>
Model For Input: {{myValObj2}}
</div>

access identifier of <input> in ng-disabled

I need to disable input field until its dependent fields have valid value.
I want to have a generic function for this.
But for this, I need to know which input field's ng-disabled method is called.
I'll have a map, using which I will check if the modelValue of its dependent fields are defined and set ng-disabled based on this.
HTML:
<input type="text" class="form-control"
ng-init="oeMinLength = '3'"
ng-model="vm.trade.BOAT_CUSTOMER_NAME"
ng-disabled="vm.dependencyValidation()"
id="fi-oe" name="oe">
<input type="text" class="form-control"
ng-model="vm.trade.BOAT_CONTACT"
ng-disabled="vm.dependencyValidation()"
id="fi-contact" name="contact">
Controller:
vm.dependencyValidation = function () {
var identifier = 'contact';
if (isEmpty(getDependent(identifier))) {
return false;
}
else {
true;
}
};
I do not want to pass the name/id as the parameter to vm.dependencyValidation().

Angular: update scope inside scope

I have a controller with 2 scopes:
app.controller('search', function($scope) {
$scope.value1 = '';
$scope.value2 = 'Some text' + $scope.value1;
}
And an input field:
<input type="text" ng-model="value1">
When I change value1 with the input field (which works), value2 doesn't get updated. How can I make this work?
You could follow dot rule while declaring object. That will give you prototypal inheritance thing. Both param1 & param2 will refer to the same copy of object. So that updating one would update the other one automatically.
Markup
<input type="text" ng-model="param1.value">
<input type="text" ng-model="param2.value">
Controller
app.controller('search', function($scope) {
$scope.param1 = {value : ''};
$scope.param2 = $scope.param1;
}
Demo Plunkr
Update
If you wanted to keep those variable as primitive then you should have to update them on some event like here you could do it by using ng-change directive
Markup
<input type="text" ng-model="value1" ng-change="value2 = value1 + ' something'">
Or simply you can move inline html code to you controller function to make it testable.
Markup
<input type="text" ng-model="value1" ng-change="changedValue()">
Code
$scope.changedValue = function(){
$scope.value2 = $scope.value1 + ' something'
}

Angularjs ng-required call function

It is possible make the required value dependet of some funcion?
Something like this? I want to do this because I want to change the required attribute to some form inputs...
HTML:
Name: <input type="text" ng-model="user.name" ng-required="isRequired('name')" />
Age: <input type="text" ng-model="user.age" ng-required="isRequired('age')" />
JS:
$scope.isRequired(fieldName){
$scope.requiredFields = [];
//$scope.requiredFields = STUFF FROM SOME REST SERVICE
for (i in requiredFields) {
if (requiredFields[i] == fieldName){
return true;
}
}
return false;
}
Updated Answer:
So based on your updated OP, what you want is certainly doable. The problem with what you were trying to do is that ng-required has no ability to execute a function, it only reads a boolean. But we can dynamically create variables based on data from the server to automatically set fields to required:
Updated Plunker
<form>
Name: <input type="text" ng-model="user.test" ng-required="name" /><br/>
<input type="text" ng-model="user.name" ng-required="age" />
<br/>
<button type="submit">Submit</button>
</form>
Note that I put a $scope property for each input in the ng-required attribute. Now we can dynamically create that $scope property and set it to true if our data says we need to:
$scope.isRequired = function(){
$scope.requiredFields = [];
$http.get('fields.json')
.success(function(data){
$scope.requiredFields = angular.fromJson(data);
console.log($scope.requiredFields.required)
for (i = 0; i < $scope.requiredFields.required.length; i++) {
$scope[$scope.requiredFields.required[i]] = true
}
console.log($scope[$scope.requiredFields.required[0]]);
})
//$scope.requiredFields = STUFF FROM SOME REST SERVICE
}
$scope.isRequired()
So it is iterating over an array of required fields received from the server, and then dynamically creating a $scope property for each one that is required, and setting it to true. Any field that has that $scope property in it's ng-required will be required now. Anything not dynamically created will just return false, and ng-required doesn't trigger.
Original answer:
Plunker
As Pratik mentioned, ng-required only accepts a Boolean value, but we can toggle the value of that with a function.
HTML
<form>
Name: <input type="text" ng-model="user.name" ng-required="isRequired" />
<br/><button ng-click="toggle()">Required: {{isRequired}}</button>
<button type="submit">Submit</button>
</form>
code:
$scope.isRequired = true;
$scope.toggle = function() {
$scope.isRequired = !$scope.isRequired;
}
I know this is a couple of years old and so AngularJS may have changed, but the accepted answer as it stands today isn't correct. You can very easily execute a function within ng-required, as it takes an expression, which can be a function. For example:
index.html
<div ng-controller="ExampleController" class="expressions">
Expression:
<input type='text' ng-model="expr" size="80"/>
<button ng-click="addExp(expr)">Evaluate</button>
<ul>
<li ng-repeat="expr in exprs track by $index">
[ X ]
<code>{{expr}}</code> => <span ng-bind="$parent.$eval(expr)"></span>
</li>
</ul>
</div>
script.js
angular.module('expressionExample', [])
.controller('ExampleController', ['$scope', function($scope) {
var exprs = $scope.exprs = [];
$scope.expr = '3*10|currency';
$scope.addExp = function(expr) {
exprs.push(expr);
};
$scope.removeExp = function(index) {
exprs.splice(index, 1);
};
}]);
In script.js, a function addExp is defined and added to the scope, and then it's called in the ng-click directive of the a tag, which also takes an expression as its argument.
This code is taken directly from the AngularJS documentation on expressions. It doesn't use ng-require directly, but any directive that takes an expression will work the same. I have used the same syntax to use a function for ng-require.

Categories