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);
});
}
Related
I'm making a basic todo app in angularjs.
Here's the code that's used to create a new todo with a checkbox
<div class="container" ng-controller = 'controller' >
<h3>Enter Todo </h3> <input type="text" ng-model = 'new'>
<button ng-click = 'add();' ng-disabled="status();">Add</button>
<div ng-repeat = "i in todo" >
<input type="checkbox" ng-model = "todo.done" /> <label>{{i.name}}</label>
</div>
</div>
The problem is that all the checkboxes get checked even when I check just one
Here's my controller module
todoApp.controller('controller',['$scope',function($scope){
$scope.new = '';
$scope.todo = [];
$scope.add = function(){
$scope.todo.push({name : $scope.new, done: false});
console.log($scope.todo);
$scope.new = '';
};
$scope.status = function(){
return !(/\S+/.test($scope.new));
};
ng-model = "i.done"
should solve the problem. In your version ng-model = "todo.done" todo is an array and angular just creates a property on the fly, when it's used for the first time. This way all of your checkboxes are connected to this property, that's why checking one checkbox affects all of them.
Because the list of the checkbox are sharing the same model. You can create a custom directive or you can use checklist-model directive.
Demo URL:
https://vitalets.github.io/checklist-model/
$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);
}
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.
If I do this {{newStore1}} and $scope.newStore1 = 'Owl Store';, when the page loads, the text says Owl Store. That data binding's all good. If I make an input box and give it the model newStoreName, that works too, for the most part...
{{newStore1}}
<form data-ng-submit="storeUpdate()">
<input type="text" ng-model="newStore1">
<input type="submit" />
</form>
The new store name shows as null. Even though as I type in the text box, the {{newStore}} updates with the text. but when I do this, it gives me a null value.
$scope.storeUpdate = function(){
Users.get({email:$scope.global.user.email}, function(user3) {
user3[0].store.push($scope.newStore1); // $scope.newStore1 is working in html but is 'null' here
user3[0].$update(function(response) {
Users.query({}, function(users) {
$scope.users = users;
$scope.global.user = response;
});
});
});
};
in your controller define:
$scope.store = {};
or if you do not want to declare it in your controller, in your HTML you need to declare the model at high level like:
<div ng-model="store.name">
{{store.name}}
<form data-ng-submit="storeUpdate()">
<input type="text" ng-model="store.name">
<input type="submit" />
</form>
<div>
Here is my situation, I have this HTML:
<input type="text" ng-model="inputModel" />
<div class="button-container">
<button type="button" ng-click="setValue(inputModel)"></button>
</div>
<input type="text" ng-model="inputModelTwo" />
<div class="button-container">
<button type="button" ng-click="setValue(inputModelTwo)"></button>
</div>
And my view controller:
$scope.setValue = function (valueToSet) {
valueToSet = "Some value.";
};
I need to be able to "connect" the input fields and their buttons and I'm doing this by having the respective button pass the respective input field's model to the controller to be modified. The problem is that when I click the button the function fires off and valueToSet is changed but the change isn't reflected back in the view! What am I missing?
If you are trying to dynamically pass in your models as a function parameter, you'll need to access a PROPERTY on the models by using dot notation.
Try defining the models in the controller like so:
$scope.inputModel = {};
$scope.inputModelTwo = {};
$scope.inputModel.text = 'hey';
$scope.inputModelTwo.text = 'ho';
Then pass in the entire model to the function as you were already doing.
Inside the function, alter the property that you desire (in this case 'text'), like so:
$scope.setValue = function (valueToSet) {
console.log(valueToSet);
valueToSet.text = "Some value.";
};
JSFiddle