Unable to reset the radio-button value in angular.js - javascript

I have two radio buttons where NO is the deault. Once a user clicks on the YES option I am saving this value and trying to make YES as the checked radio button. But I am unable to edit the default value once user changes their option. Here is my code:
<body ng-app="mainModule" class="">
<div ng-controller="AdminConfigController">
<div class="aui-page-panel aui-page-focused aui-page-focused-small" id = "continueDiscovery">
<div class ="aui-page-panel-inner">
<section class="aui-page-panel-content" >
<label>Use User Story template while creating JIRA issue for Product features?</label>
<div ng-repeat="eval in getEvaluators()">
<label class="radio" >
<input type="radio" ng-model="cell.evaluator" ng-click ="setConfig(cell.evaluator)" name="evaluatorOptions" value="\{{eval.name}}">\{{eval.name}}
</label>
</div>
<hr />
<div>You picked: \{{cell.evaluator}}</div>
</section>
</div>
</div>
</div>
</body>
Controller code:
angular.module('mainModule').controller('AdminConfigController', function($scope, $http){
$scope.cell = function() {
return $http.get('/getAdminConfig/').success(function(data){
template = data[0].userTemplate;
}).error(function(data){
console.log('Error: ' + data)
});
};
$scope.cell = {
evaluator: "NO"
};
$scope.updateCell = function (option) {
$scope.cell = {
evaluator: option
};
console.log($scope.cell)
}
$scope.evaluators = [{
name: "YES"
}, {
name: "NO"
}];
$scope.getEvaluators = function () {
return $scope.evaluators;
};
$scope.setConfig = function (option) {
console.log("Config Choice:" + option)
updateCell(option)
$scope.option = option
console.log("Entry Choice"+ $scope.option)
var data = {
userTemplate : $scope.option
}
$http.delete('/resetConfig/').success(function(data){
}).error(function(data){
console.log('Error: ' + data)
});
$http.post('/setAdminConfig/' , data).success(function(data){
console.log(data)
/*$scope.productDiscoveryData = data;*/
}).error(function(data){
console.log('Error: ' + data)
});
};
});
So if you look at the controller code I need to change the default value
$scope.cell = {
evaluator: "NO"
};
to the option selected by the user.

I Hope this code help you.
function AdminConfigController ($scope){
$scope.Message = 'Hello Hi !';
$scope.getEvaluators = function () {
$scope.evaluators = [{name: "YES"}, {name: "NO"}];
return $scope.evaluators;
};
$scope.cell = {
evaluator: "NO"
};
$scope.updateCell = function (option) {
$scope.cell = {
evaluator: option
};
console.log($scope.cell)
}
$scope.setConfig = function (option) {
console.log("Config Choice:" + option)
$scope.updateCell(option);
$scope.option = option
console.log("Entry Choice"+ $scope.option)
var data = {
userTemplate : $scope.option
}
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<body ng-app="" class="">
<div ng-controller="AdminConfigController"> {{Message}}
<div class="aui-page-panel aui-page-focused aui-page-focused-small" id = "continueDiscovery">
<div class ="aui-page-panel-inner">
<section class="aui-page-panel-content" >
<label>Use User Story template while creating JIRA issue for Product features?</label>
<div ng-repeat="eval in getEvaluators()"> {{$scope.cell.evaluator}}
<label class="radio" >
<input type="radio" name="evaluatorOptions" ng-model="cell.evaluator" value={{eval.name}}>\{{eval.name}}
</label>
</div>
<hr />
<div>You picked: \{{cell.evaluator}}</div>
</section>
</div>
</div>
</div>
</body>

Related

precheck checkboxes depending on the response coming in json form in vuejs

Sorry for my English. I am trying to pre select those checkboxes whos values have been saved in the database. I did it using javascript in vuejs but those selected checkboxes values are not storing in array.
My code is like
role.component.js
getRoleRowData(data) {
this.roleaction = "edit";
this.addrolemodal = true;
console.log(data.role_id);
axios
.post(apiUrl.api_url + "getRolePermissionData", {
role_id: data.role_id
}).then(
result => {
this.permid = result.data;
var list = [];
result.data.forEach(function(value) {
list.push(value.perm_id);
});
var options = list;
for (var i = 0; i < options.length; i++) {
if (options[i]) document.querySelectorAll('input[value="' + options[i] + '"][type="checkbox"]')[0].checked = true;
}
},
error => {
console.error(error);
}
);
this.addrole = data;
},
And role.component.html
<div class="col-md-8">
<b-form-fieldset>
<div class="form" id="demo">
<h6>Permissions</h6>
<span v-for="perm_name_obj in listPermissionData">
<input type="checkbox" class="perm_id" v-bind:value="perm_name_obj.perm_id" name="perm_id" id="perm_name" v-model="checkedPerm_Id"> {{perm_name_obj.perm_name}}<br>
</span>
<span>Checked names: {{ checkedPerm_Id }}</span>
</div>
</b-form-fieldset>
</div>
And the Output
And the Ouput I got
In simple words I want to pre check checkboxes in vuejs of which values are stored in database.
See the following example, using simulation data
var app = new Vue({
el: '#app',
data () {
return {
listPermissionData: [],
checkedPerm_Id: []
}
},
created () {
setTimeout(_=>{
//Here simulates axois to request Permission data
this.listPermissionData = [
{perm_id:1,perm_name:'perm_name1'},
{perm_id:2,perm_name:'perm_name2'},
{perm_id:3,perm_name:'perm_name3'},
{perm_id:4,perm_name:'perm_name4'},
{perm_id:5,perm_name:'perm_name5'}
];
//Here simulates axois to request Selected Permissions (result.data)
var selected = [
{perm_id:2,perm_name:'perm_name2'},
{perm_id:5,perm_name:'perm_name5'}
]
this.checkedPerm_Id = selected.map(o=>o.perm_id)
},1000)
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<div class="form">
<h6>Permissions</h6>
<span v-for="perm_name_obj in listPermissionData">
<input type="checkbox" class="perm_id" v-bind:value="perm_name_obj.perm_id" name="perm_id" id="perm_name" v-model="checkedPerm_Id"> {{perm_name_obj.perm_name}}<br>
</span>
<span>Checked names: {{ checkedPerm_Id }}</span>
</div>
</div>
I solved my problem, here is my code
role.component.js
getRoleRowData(data) {
this.roleaction = "edit";
this.addrolemodal = true;
console.log(data.role_id);
let tempthis = this;
axios
.post(apiUrl.api_url + "getRolePermissionData", {
role_id: data.role_id
}).then(
result => {
this.permid = result.data;
var list = [];
result.data.forEach(function(value) {
//by using tempthis variable we provided the current access to the checkedPerm_Id array which not accessible from out of the function which is getRoleRowData
tempthis.checkedPerm_Id.push(value.perm_id);
list.push(value.perm_id);
});
},
error => {
console.error(error);
}
);
this.addrole = data;
},

ng-click(parameters) open a popup window with dropdown,then selected item and parameters sent to the service

I'm new to Angular-js. I'm using JSP for front end and passing values from UI to controller.Now I need to open a new popup list where user can select an option, then pass all parameters to service ..
ng-click="rewardRetry(singleWinner)"
controller --->
$scope.retryRewardDTO = {
"mobile_number" : null,
"draw_id" : 0,
"lottery_ticket_id" : 0,
"prize" : 0,
"reward_method" :null
};
(mobile_number,draw_id,lottery_ticket_id,prize) I can assign like this
$scope.rewardRetry = rewardRetry;
function rewardRetry(rewardRetryDTO) {
$scope.retryRewardDTO.draw_id=rewardRetryDTO.draw_id;
$scope.retryRewardDTO.lottery_ticket_id=rewardRetryDTO.lottery_ticket_id;
$scope.retryRewardDTO.prize=rewardRetryDTO.prize;
$scope.retryRewardDTO.mobile_number=rewardRetryDTO.mobile_number;
//$scope.retryRewardDTO.reward_method=rewardRetryDTO.reward_method;
}
But here retryRewardDTO.reward_method -->user should be select in popup option. (wallet,m_cash,reload,,, ....etc)
calling to service
winnerService.winnerService.rewardRetry(
$scope.retryRewardDTO,
function(data, headers) {
winnerSearch();
}, function() {
});
I'm trying do something like below link.but couldn't get a proper output.please some helps to me...
visit :AngularJS Modal Popup
Finally I found the answer and here implemented new rewardService
$scope.rewardRetry = rewardRetry;
function rewardRetry(rewardRetryDTO) {
$scope.retryRewardDTO.draw_id=rewardRetryDTO.draw_id;
$scope.retryRewardDTO.lottery_ticket_id=rewardRetryDTO.lottery_ticket_id;
$scope.retryRewardDTO.prize=rewardRetryDTO.prize;
$scope.retryRewardDTO.mobile_number=rewardRetryDTO.mobile_number;
//$scope.retryRewardDTO.reward_method=rewardRetryDTO.reward_method;
var modalOptions = {
bodyText : 'Are you sure you want to retry '+$scope.retryRewardDTO.prize+'/= reward for 0'+ $scope.retryRewardDTO.mobile_number+' ? Please select a reward method first and confirm'
};
rewardService.showModal({}, modalOptions).then(
function(result) {
$scope.retryRewardDTO.reward_method = result;
$('#retry-'+rewardRetryDTO.draw_id+'-'+rewardRetryDTO.lottery_ticket_id).hide();
$timeout(function() {
winnerService.winnerService.rewardRetry(
$scope.retryRewardDTO,
function(data, headers) {
winnerSearch();
}, function() {
});
});
});
}
;
My reward_option.jsp file
<%# taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<div class="option">
<div class="pull-right"></div>
<div>Copyright © Lucky889 2016</div>
<input type="hidden" value="<sec:authentication property="principal.userType" />" id="user_type" />
<input type="hidden" value="<sec:authentication property="principal.operator" />" id="user_operator" />
</div>
<script type="text/ng-template" id="rewardModalContent.html">
<div class="modal-header">
<h3>{{modalOptions.headerText}}</h3>
</div>
<div class="modal-body">
<p>{{modalOptions.bodyText}}</p>
<div class="modal-body">
<%-- <p ng-repeat="(key,singleReward) in modalOptions.rewardList">{{key}}----{{singleReward}}</p> --%>
<div class="form-group">
<label class="control-label" for="reward">Reward
Method</label><select name="reward" id="reward"
ng-model="reward_method" class="form-control">
<option ng-repeat="(key,singleReward) in modalOptions.rewardList"
value="{{key}}">{{singleReward}}</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary"
data-ng-click="modalOptions.confirm(reward_method)">{{modalOptions.actionButtonText}}</button>
<button type="button" class="btn"
data-ng-click="modalOptions.cancel()">{{modalOptions.closeButtonText}}</button>
</div>
</script>
Here is my rewardService
angular.module("zmessengerRewardApp.service", []).service(
'rewardService',
function(toastr, $uibModal, $log) {
var showHeaderErrorMessage = function(header) {
toastr.clear();
toastr.error(header['lms-message'],
header['lms-root-cause-message']);
};
var showHeaderSuccessMessage = function(header) {
toastr.clear();
toastr.success(header['lms-message'],
header['lms-root-cause-message']);
};
var modalDefaults = {
backdrop : true,
keyboard : true,
modalFade : true,
templateUrl : 'rewardModalContent.html'
};
var modalOptions = {
closeButtonText : 'Cancel',
actionButtonText : 'Confirm',
headerText : 'Confirmation',
bodyText : 'Perform this action?',
rewardList : {reload:'Auto Reload',manual_reload:'Manual Reload',ez_cash:'Ezcash',mcash:'MCash',wallet:'Wallet',bank:'Bank Transfer'}
};
function showModal(customModalDefaults, customModalOptions) {
if (!customModalDefaults)
customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return show(customModalDefaults, customModalOptions);
};
function show(customModalDefaults, customModalOptions) {
// Create temp objects to work with since we're in a singleton
// service
var tempModalDefaults = {};
var tempModalOptions = {};
// Map angular-ui modal custom defaults to modal defaults
// defined in service
angular.extend(tempModalDefaults, modalDefaults,
customModalDefaults);
// Map modal.html $scope custom properties to defaults defined
// in service
angular.extend(tempModalOptions, modalOptions,
customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function($scope,
$uibModalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.confirm = function(result) {
$uibModalInstance.close(result);
};
$scope.modalOptions.cancel = function(result) {
$uibModalInstance.dismiss('cancel');
};
}
}
return $uibModal.open(tempModalDefaults).result;
};
return {
showHeaderErrorMessage : showHeaderErrorMessage,
showHeaderSuccessMessage : showHeaderSuccessMessage,
showModal : showModal,
};
});

Link div and textbox value on div selection

I am trying to sync div with textbox.
For example, I created 2 nodes i.e Node 1 and Node 2 and when I select node1 and I enter title and location then title and location should sync with Node1 so when I enter title while I have selected node1 then title value should get reflected for node1 and after entering title and location next time when I select node1 then title and location value should be reflected in my textbox.
I created this below Fiddle to demonstrate the problem : http://jsfiddle.net/quk6wtLx/2/
$scope.add = function (data) {
var post = data.nodes.length + 1;
var newName = data.name + '-' + post;
data.nodes.push({ name: newName, nodes: [],selected : false });
};
$scope.tree = [{ name: "Node", nodes: [], selected: false }];
$scope.setActive = function (data) {
clearDivSelection($scope.tree);
console.log(data);
data.selected = true;
};
I am not getting how to do this.
You need to bind the form elements with the data you are appending to the tree.
Check this snippet
var app = angular.module("myApp", []);
app.controller("TreeController", function ($scope) {
$scope.delete = function (data) {
data.nodes = [];
};
$scope.add = function (data) {
var post = data.nodes.length + 1;
var newName = data.name + '-' + post;
data.nodes.push({ name: newName, nodes: [],selected : false, myObj: { name: newName} });
};
$scope.tree = [{ name: "Node", nodes: [], selected: false }];
$scope.setActive = function ($event, data) {
$event.stopPropagation();
$scope.selectedData = data;
clearDivSelection($scope.tree);
data.selected = true;
};
function clearDivSelection(items) {
items.forEach(function (item) {
item.selected = false;
if (item.nodes) {
clearDivSelection(item.nodes);
}
});
}
});
ul {
list-style: circle;
}
li {
margin-left: 20px;
}
.active { background-color: #ccffcc;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="TreeController">
<li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li>
<script type="text/ng-template" id="tree_item_renderer.html">
<div ng-class="{'active': data.selected}" > {{data.myObj.name}}</div>
<button ng-click="add(data)">Add node</button>
<button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>
<ul>
<li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'" ng-click="setActive($event, data)"></li>
</ul>
</script>
<div style="margin-left:100px;">
Title : <input type="text" ng-model="selectedData.myObj.name" />
Location : <input type="text" ng-model="selectedData.myObj.location" />
</div>
</ul>
You can check the binding documentation for AngularJs and all the possibilities https://docs.angularjs.org/guide/databinding

AngularJS custom filter with checkbox and radio button

My application has to dynamically list file items using a Radio button, Checkbox and AngularJS custom filter (code given below).
I have tried few options, but could not get the working code.
I have created the fiddle link and find the same below:
https://jsfiddle.net/38m1510d/6/
Could you please help me to complete the below code to list the file items dynamically ?
Thank you.
<div ng-app="myApp" ng-controller="myCtrl">
<label>
<input type="radio" ng-model="inputCreatedBy" value="byX"
ng-click="myFilter(?, ?)"> by X
<input type="radio" ng-model="inputCreatedBy" value="byAll"
ng-click="myFilter(?, ?)"> by All
</label> <br/><br/>
<label>
<input type='checkbox' ng-model='Type1Files' ng-change='myFilter(?, ?)'>Type1 files
<input type='checkbox' ng-model='Type2Files' ng-change='myFilter(?, ?)'>Type2 files
</label>
<br/><br/>
<label ng-repeat="file in displayFiles | filter: myFilter(createdBy, fileType)">
{{ file.name }}
</label>
</div>
</body>
<script>
var app = angular.module("myApp",[]);
app.controller('myCtrl', function ($scope) {
$scope.files = [
{ name: 'file1', type:'Type1', createdBy: 'X' },
{ name: 'file2', type:'Type2', createdBy: 'X' },
{ name: 'file3', type:'Type2', createdBy: 'Y' },
{ name: 'file4', type:'Type1', createdBy: 'Y' }
];
$scope.displayFiles = [];
$scope.myFilter = function() {
return new function(createdBy, fileType) {
var displayFilesTemp = [];
for(i=0;i<$scope.files.length;i++) {
if($scope.files[i].type ==fileType && $scope.files[i].createdBy == createdBy && !checkArrayContainsObject(displayFilesTemp, displayFiles[i])) {
displayFilesTemp.push(displayFiles[i]);
}
}
return displayFilesTemp;
};
};
});
function checkArrayContainsObject(a, obj) {
for (var i = 0; i < a.length; i++) {
if (JSON.stringify(a[i]) == JSON.stringify(obj)) {
return true;
}
}
return false;
}
</script>
Here's a working fiddle - http://jsfiddle.net/1gfaocLb/
Radio is a unique value, so it's easy to filter by.
Selected types are array of values so it's needs a little more attention.
myApp.filter('typesFilter', function() {
return function(files, types) {
return files.filter(function(file) {
if(types.indexOf(file.type) > -1){
return true;
}else{
return false;
}
});
};
});
According the shared code / fiddle, I've simplified the code for a possible solution. The file filtering logic is not foreseen since it was not clear what needed to be done exact.
<body ng-app="myapp">
<div ng-controller="myctrl">
<label>
<input type="radio" ng-model="inputCreatedBy" value="byX"
ng-click="filterFiles()"> by X
<input type="radio" ng-model="inputCreatedBy" value="byAll"
ng-click="filterFiles()"> by All
</label> <br/><br/>
<label>
<input type='checkbox' ng-model='Type1Files' ng-change='filterFiles()'>Type1 files
<input type='checkbox' ng-model='Type2Files' ng-change='filterFiles()'>Type2 files
</label>
<br/><br/>
<label ng-repeat="file in filteredFiles">
{{ file.name }} <br/>
</label>
</div>
</body>
var app = angular.module("myapp",[])
app.controller('myctrl', function ($scope) {
$scope.files = [
{ name: 'file1', type:'Type1', createdBy: 'X' },
{ name: 'file2', type:'Type2', createdBy: 'X' },
{ name: 'file3', type:'Type2', createdBy: 'Y' },
{ name: 'file4', type:'Type1', createdBy: 'Y' }
];
$scope.filterFiles = function(){
// init dict
var files = [];
// loop & check files
angular.forEach($scope.files, function(value, key) {
// do file check and push to files.push when matching with criteria
files.push(value);
});
// set scope files
$scope.filteredFiles = files;
}
// init filter on ctrl load
$scope.filterFiles();
});
First, you don't have to use any directive as ng-if/ng-click to achieve what you want. Just changing how the values are binding into the radio button and checkbox can do the trick. Also you just need to do a custom filter to handle the checkbox selections, since radio button is unique. Take a look on my solution:
angular.module("myApp", [])
.controller('myCtrl', function($scope) {
$scope.files = [
{
"name":"file1",
"type":"Type1",
"createdBy":"X"
},
{
"name":"file2",
"type":"Type2",
"createdBy":"X"
},
{
"name":"file3",
"type":"Type2",
"createdBy":"Y"
},
{
"name":"file4",
"type":"Type1",
"createdBy":"Y"
}
];
})
.filter('typesFilter', function() {
return function(files, types) {
if (!types || (!types['Type1'] && !types['Type2'])) {
return files;
}
return files.filter(function(file) {
return types['Type1'] && file.type == 'Type1' || types['Type2'] && file.type == 'Type2';
});
};
});
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<form action="" name="form">
Created by:
<input type="radio" id="radio1" ng-model="criteria.createdBy" value="X">
<label for="radio1">by X</label>
<input type="radio" id="radio2" ng-model="criteria.createdBy" value="">
<label for="radio2">by All</label>
<br/>
<br/>
Type:
<input type="checkbox" id="check1" ng-model="criteria.type['Type1']">
<label for="check1">Type1 files</label>
<input type="checkbox" id="check2" ng-model="criteria.type['Type2']">
<label for="check2">Type2 files</label>
</form>
<pre ng-bind="criteria | json"></pre>
<div ng-repeat="file in files | filter: { createdBy: criteria.createdBy } | typesFilter: criteria.type" ng-bind="file.name"></div>
</body>
</html>

Node/AngularJS - TypeError: Cannot read property '_id' of undefined.

I am new to the MEAN and i am trying to make a simple CRUD application. I am getting an error of undefined on my _id and i do not understand why. This variable works withevery other function I call it in. Hopefully someone can help. I am getting the error on line 117 in my controller.js file
Here is the controller.js code for my application
todoApp.controller('TodoCtrl', function($rootScope, $scope, todosFactory) {
$scope.todos = [];
$scope.isEditable = [];
// get all Todos on Load
todosFactory.getTodos().then(function(data) {
$scope.todos = data.data;
});
// Save a Todo to the server
$scope.save = function($event) {
if ($event.which == 13 && $scope.todoInput) {
todosFactory.saveTodo({
"todo": $scope.todoInput,
"isCompleted": false
}).then(function(data) {
$scope.todos.push(data.data);
});
$scope.todoInput = '';
}
};
//update the status of the Todo
$scope.updateStatus = function($event, _id, i) {
var cbk = $event.target.checked;
var _t = $scope.todos[i];
todosFactory.updateTodo({
_id: _id,
isCompleted: cbk,
todo: _t.todo
}).then(function(data) {
if (data.data.updatedExisting) {
_t.isCompleted = cbk;
} else {
alert('Oops something went wrong!');
}
});
};
// Update the edited Todo
$scope.edit = function($event, i) {
if ($event.which == 13 && $event.target.value.trim()) {
var _t = $scope.todos[i];
todosFactory.updateTodo({
_id: _t._id,
todo: $event.target.value.trim(),
isCompleted: _t.isCompleted
}).then(function(data) {
if (data.data.updatedExisting) {
_t.todo = $event.target.value.trim();
$scope.isEditable[i] = false;
} else {
alert('Oops something went wrong!');
}
});
}
};
// Delete a Todo
$scope.delete = function(i) {
todosFactory.deleteTodo($scope.todos[i]._id).then(function(data) {
if (data.data) {
$scope.todos.splice(i, 1);
}
});
};
});
todoApp.controller('TodoCtrl', function($rootScope, $scope, todosFactory) {
$scope.todos = [];
$scope.isEditable = [];
// get all Todos on Load
todosFactory.getTodos().then(function(data) {
$scope.todos = data.data;
});
// Save a Todo to the server
$scope.save = function($event) {
if ($event.which == 13 && $scope.todoInput) {
todosFactory.saveTodo({
"todo": $scope.todoInput,
"isCompleted": false
}).then(function(data) {
$scope.todos.push(data.data);
});
$scope.todoInput = '';
}
};
//update the status of the Todo
$scope.updateStatus = function($event, _id, i) {
var cbk = $event.target.checked;
var _t = $scope.todos[i];
todosFactory.updateTodo({
_id: _id,
isCompleted: cbk,
todo: _t.todo
}).then(function(data) {
if (data.data.updatedExisting) {
_t.isCompleted = cbk;
} else {
alert('Oops something went wrong!');
}
});
};
// Update the edited Todo
$scope.edit = function($event, i) {
if ($event.which == 13 && $event.target.value.trim()) {
var _t = $scope.todos[i];
todosFactory.updateTodo({
_id: _t._id,
todo: $event.target.value.trim(),
isCompleted: _t.isCompleted
}).then(function(data) {
if (data.data.updatedExisting) {
_t.todo = $event.target.value.trim();
$scope.isEditable[i] = false;
} else {
alert('Oops something went wrong!');
}
});
}
};
// Delete a Todo
$scope.delete = function(i) {
todosFactory.deleteTodo($scope.todos[i]._id).then(function(data) {
if (data.data) {
$scope.todos.splice(i, 1);
}
});
};
});
Just is case the error is in either my factory.js code or html, I will include both.
Here is the factory.js code:
todoApp.factory('todosFactory', function($http){
var urlBase = '/api/todos';
var _todoService = {};
_todoService.getTodos = function(){
return $http.get(urlBase);
};
_todoService.saveTodo = function(todo){
return $http.post(urlBase, todo);
};
_todoService.updateTodo = function(todo) {
return $http.put(urlBase, todo);
};
_todoService.deleteTodo = function(id){
return $http.delete(urlBase + '/' + id);
};
return _todoService;
});
Here the html partial that uses the controller and factory:
<div class="container" ng-controller="TodoCtrl">
<div class="row col-md-12">
<div>
<input type="text" class="form-control input-lg" placeholder="Enter a todo" ng-keypress="save($event)" ng-model="todoInput">
</div>
</div>
<div class="row col-md-12 todos">
<div class="alert alert-info text-center" ng-hide="todos.length > 0">
<h3>Nothing Yet!</h3>
</div>
<div ng-repeat="todo in todos" class=" col-md-12 col-sm-12 col-xs-12" ng-class="todo.isCompleted ? 'strike' : ''">
<div class="col-md-1 col-sm-1 col-xs-1">
<input type="checkbox" ng-checked="todo.isCompleted" ng-click="updateStatus($event, todo._id, $index)">
</div>
<div class="col-md-8 col-sm-8 col-xs-8">
<span ng-show="!isEditable[$index]">{{todo.todo}}</span>
<input ng-show="isEditable[$index]" type="text" value="{{todo.todo}}" ng-keypress="edit($event)">
<input ng-show="isEditable[$index]" type="button" class="btn btn-warning" value="Cancel" ng-click="isEditable[$index] = false" />
</div>
<div class="col-md-3 col-sm-3 col-xs-3" >
<input type="button" class="btn btn-info" ng-disabled="todo.isCompleted" class="pull-right" value="edit" ng-click="isEditable[$index] = true" />
<input type="button" class="btn btn-danger" class="pull-right" value="Delete" ng- click="delete($index)" />
</div>
</div>
</div>
This line must be the cause of the issue:
<input ng-show="isEditable[$index]" type="text" value="{{todo.todo}}"
ng-keypress="edit($event)">
You forgot to pass the $index as the second parameter of the edit function. This should fix it:
<input ng-show="isEditable[$index]" type="text" value="{{todo.todo}}"
ng-keypress="edit($event, $index)">

Categories

Resources