delete the selected item from list - angularjs

Im using ionic framework and Im trying to create a phone list which can add and delete the user entered phone no.Here the user entered numbers are listed with check box on clicking the add button.When the user selects the check-box and clicks the delete button, he must be able to delete the selected check box phone number.Here the problem is while using the delete button, it doesn't delete the selected check box instead it is deleting the first value entered in the list. So please help me to delete only user selected check-box items.
html code:
<div>
<ion-checkbox ng-model="phoneno" ng-repeat="y in phonelist">
<span data-ng-bind="y"> {{y}}</span> </ion-checkbox>
<button ng-click="remove($index)" value="Delete">Delete</button><br>
</div>
<br>
<br>
<div>
<!label class="item item-input item-floating-label">
<input ng-maxlength="10" ng-model="phone"> <br>
<button ng-click="add()" value="Add">Add</button><br>
<!/label>
</div>
</ion-content >
</ion-view>
js code:
.controller('PlaylistCtrl', function($scope, $stateParams) {
})
.controller('addAdmin',['$scope',function($scope){
$scope.phonelist=[];
$scope.add=function(phone){
$scope.phonelist.push($scope.phone);
$scope.phone='';
}
$scope.remove=function(uuid){
var x=$scope.phonelist[uuid];
$scope.phonelist.splice(uuid,1);
}
}]);

Sorry for my english. I'm foreigner..
The problem is that your loop ends before the button, so when the button gets clicked the $index is always 0.
Because its not inside the element "ion-checkbox".
Here is my solution: put ng-click inside the checkbox and call to function with the $index.
And in the js, save the index on a scope var. So if the delete button gets clicked, delete the index that you saved on the previous function.
I hope that i helped.

It seems like you mean something else than your code says. You probably want to delete all phones that are checked, when clicking the button. Therefore you don't need the $index property, but just loop through the phones and delete the ones that are checked.
You will have to keep track of a 'checked' property of each phone, so you know which are checked. You can do this by using an object which holds the phone information, instead of just a string:
<div>
<!-- ng-model to a property of the phone that keeps track if the phone is checked -->
<ion-checkbox ng-model="y.checked"
ng-repeat="y in phonelist">
<span data-ng-bind="y.number">{{ y.number }}</span>
</ion-checkbox>
<button ng-click="removeSelected()" value="Delete">Delete</button><br>
</div>
<!-- ng-model to a property of the phone object -->
<input type="text" ng-model="phone.number" />
And in your controller:
$scope.add = function() {
$scope.phonelist.push($scope.phone);
}
$scope.removeSelected = function() {
var i = $scope.phonelist.length;
// reversed loop because you change the array
while (i--) {
var phone = $scope.phonelist[i];
// If phone is checked, remove from list
if(phone.checked) {
$scope.phonelist.splice(i, 1);
}
}
}
See this jsfiddle
Or see this jsfiddle where I included Ionic

It seems that you're mixing the add and remove functions, try to separate those as below.
.controller('addAdmin',['$scope',function($scope){
$scope.phonelist=[];
//Add function
$scope.add=function(phone){
$scope.phonelist.push(phone);
$scope.phone='';
}
//Remove function
$scope.remove = function(index){
$scope.phonelist.splice(index, 1);
};
}]);

add the following code in your controller
$scope.remove = function(index){
$scope.phonelist.splice(index, 1);
}
and that should work

Related

How to delete the textbox when button is clicked in angularjs?

What I am trying is to expand the button when button is clicked..At the same time when u want to delete the textbox I am unable identify the process.The first appending of text boxes had been done in the below fiddle.can anyone solve for delete operation
http://plnkr.co/edit/pI9BSWVLYxiSK2bbKuJW?p=preview
to add text boxes
//
$scope.addContact = function() {
$scope.contacts.push({
})
}
HTML
<li ng-repeat="contact in contacts track by $index">
<input type="text" /><button ng-click="removeContact($index)">-</button>
</li>
Notice I have added a removeContact() method to the button and this is the method:
$scope.removeContact = function(index) {
$scope.contacts.splice(index, 1);
}
Here is the plnkr

Angularjs Dropdown closes when $location.search parameters are changed

I'm building an ecommerce site. I have a directive called "horizontalShoppingByCategoriesLayout" that watches the current filter criteria (to filter products being returned) and as the user changes those filter criteria the directive sets the search parameters $location.search(..).
...
filterParameters['searchtext'] = $scope.searchText;
filterParameters['order'] = searchorder;
filterParameters['page'] = page;
filterParameters['limit'] = limit;
$location.search(filterParameters);
On that same directive my code is set up to watch the url, and if it changes (due to changes in filter criteria) then to do a search to return products.
$scope.$watch(function () { return $location.url(); }, function (url){
if (url){
$timeout(function() {
getProducts();
});
}
});
The filter criteria are defined in a directive called "filterCriteriaVarietyCategoriesHorizontal" that is defined in the template of "horizontalShoppingByCategoriesLayout".
<div class="pull-leftt" ng-if='numberProducts != undefined && numberProducts > 0'>
<filter-criteria-horizontal execute-criteria-search=$parent.executeCriteriaSearch category-id=$parent.categoryId search-criteria-list=$parent.searchCriteriaList></filter-criteria-horizontal>
</div>
When a user hovers over the filter criteria category button, this triggers an angular event that causes an Angular-UI Bootstrap dropdown to drop down and show the options for that filter criteria category. The user can then click on the filter criteria option, which "horizontalShoppingByCategoriesLayout" detects and then calls a change on the $location search parameters (which changes the url and a webservice call for products is initiated).
The filter criteria options in the dropdown are a set of checkboxes. My problem is when the user clicks on one of these checkboxes, it causes the dropdown to close, which should only happen when the user hovers off of the button that initiated the dropdown opening. I already fixed the problem where the clicking on the checkbox it's self causes the dropdown to close by calling ng-click="$event.stopPropagation()" on the checkbox. Here is my code for the filtercriteria category, dropdown, and checkboxes.
<div class="coll-md-12" ng-mouseleave="closeAll()">
<div class="btn-group" dropdown is-open="status.isopen">
<button ng-mouseleave="close()" ng-mouseenter="open()" type="button" ng-class="{'filter-criteria-variety-category-name-hover': filterCriteriaCategoryActive}" class="btn btn-link dropdown-toggle filter-criteria-variety-category-name" dropdown-toggle ng-disabled="disabled">
{{searchCriteria.criteriaName}}<span class="caret"></span>
</button>
<div class="dropdown-menu">
<div class="search-criteria-values" ng-mouseleave="close()" ng-mouseenter="keepOpen()">
<div ng-if="searchCriteria.imageBasedFilter == true">
<filter-criteria-options-visual filter-criteria-options=$parent.searchCriteria.criteriaOptionValues></filter-criteria-options-visual>
</div>
<div ng-if="searchCriteria.imageBasedFilter == false">
<div class="col-md-12 no-padding" ng-repeat="searchCriteriaOption in searchCriteria.criteriaOptionValues">
<div class="pull-left filter-criteria-checkbox-item">{{searchCriteriaOption.criteriaOption}} <input ng-click="$event.stopPropagation()" id="{{searchCriteriaOption.criteriaOption}}" type="checkbox" ng-model="searchCriteriaOption.checked"/></div>
</div>
</div>
</div>
</div>
</div>
I'm sure that it is adding search parameters to the url with $location.search(...) that is causing the dropdown to close because if I comment out the line that adds the (filter criteria to the) search parameters to the url in the directive "horizontalShoppingByCategoriesLayout", then the dropdown does not close.
...
filterParameters['searchtext'] = $scope.searchText;
filterParameters['order'] = searchorder;
filterParameters['page'] = page;
filterParameters['limit'] = limit;
//$location.search(filterParameters);
With the checkboxes in the dropdown I was able to stop the dropdown from closing by calling stopPropagation() on the click event, but for a change in the $location search parameters I don't know how to stopPropogation for that change.
Does anyone have an idea how to cause the dropdown to not close when changes are made to the $location.search parameters?
I had the same issue then I looked into the source code of angular boostrap ui and found:
$scope.$on('$locationChangeSuccess', function() {
scope.isOpen = false;
});
And a hacky solution would be remove the listener
$scope.$$listeners.$locationChangeSuccess = [];
in your dropdown controller
The solution from user3217868 worked well for me but I had to execute the code once the document was fully loaded like on my code below.
angular.element(document).ready(function () {
$scope.$$listeners.$locationChangeSuccess = [];
});
Posting here in case it may be helpful to someone else.

ng-click showing all the hidden text field on ng-repeat rather than one in Angular

I started to work with Angular, it's pretty good to implement, I stuck with a single issue at ng-click
I am getting data dynamically and showing with ng-repeat, and I want to update the data at pencil click and for it I am using input text element, but when I click on pencil It's opening all the text fields
Here is my HTML code
<
div ng-repeat="item in scroller.items track by $index">
<div class="secHead text-center">
<button class="common btnDarkGrey" data-ng-hide="hideCatButton">{{item.category_name}}</button>
<input type="text" id="focus-{{$index}}" class="common btnDarkGrey editDashboardCategory" name="editCategory" value="" data-ng-model="item.category_name" data-ng-show="hideField">
<span data-ng-click="updateCategory(item.category_id,item.category_name,$index)" class="chkOneDone" data-ng-show="hideOkButton">Done</span>
<div class="pull-right">
</div>
</div>
</div>
And here I Angular code
$scope.updateCategory=function(category_id,updated_cat_name, $index){
Category.updateCat($rootScope,$scope,$index,$http,$timeout,updated_cat_name,old_cat_name,category_id);
};
$scope.updatePen=function($index){
old_cat_name=$scope.scroller.items[$index].category_name
$scope.hideField=true;
$rootScope.hideOkButton=true;
$rootScope.hideCatButton=true;
};
I created a Category service to perform task like update
I didn't get any proper solution yet.
Can anybody help me?
Thank You.
If you only want to hide/show one of the elements in the list you need to specify that in some fashion. Right now you have a three rootScope booleans:
$scope.hideField=true;
$rootScope.hideOkButton=true;
$rootScope.hideCatButton=true;
being set for the entire list, and you need to set a show properties on each individual in the list.
In your controller function you can do something like this before you expect a click:
//normal for loop so that you have the index
for(var i=0; i < $scope.scroller.items.length; i++){
$scope.scroller.items[i].show = false;
}
Then you can do something like this to actually show the fields:
HTML:
div ng-repeat="item in scroller.items track by $index">
<div class="secHead text-center">
<button class="common btnDarkGrey" ng-hide="!item.show">
{{item.category_name}}</button>
<input type="text" id="focus-{{$index}}" class="common btnDarkGrey editDashboardCategory" name="editCategory" value="" ng-model="item.category_name" ng-hide="!item.show">
<span data-ng-click="updateCategory(item.category_id,item.category_name,$index)" class="chkOneDone" ng-show="item.show">Done</span>
<div class="pull-right">
</div>
</div>
</div>
Controller:
//controller declaration --
$scope.updatePen = function(index){
$scope.scroller.items[index].show = true;
};
It's my understanding that you need all three properties to show once a click happens, so I condensed all the show properties into one single show property.
Your view only sees that hideField is true and performs that action for all of the items in your array. I hope this helps!

AngularJS's ng-model icm textarea

I'm trying to add some text to the last cursor place after clicking a button.
In the controller:
$scope.addEmoji = function(name){
var element = $("#chat-msg-input-field");
element.focus(); //ie
var selection = element.getSelection();
var textBefore = $scope.chatMsg.substr(0, selection.start);
var textAfter = $scope.chatMsg.substr(selection.end);
$scope.chatMsg = textBefore + name + textAfter;
}
$scope.updateChatMsg = function(chatMsg){
$scope.chatMsg = chatMsg;
}
$scope.sendChatMsg = function(){
var backend = $scope.convs[$scope.active.conv].backend.name;
$scope.view.addChatMsg($scope.active.conv, $scope.active.user, $scope.chatMsg,new Date().getTime() / 1000, backend);
Chat[backend].on.sendChatMsg($scope.active.conv, $scope.chatMsg);
$scope.chatMsg = '';
};
And then some HTML:
<div class="chat-msg-button" >
<button ng-click="view.toggle('emojiContainer')" ><img src="/apps/chat/img/emoji/smile.png"></button>
</div>
<form id="chat-msg-form" ng-submit="sendChatMsg()">
<div class="chat-msg-button" >
<button type="submit"><div class="icon-play"> </div></button>
</div>
<div id="chat-msg-input">
<textarea id="chat-msg-input-field" autocomplete="off" type="text" ng-model="chatMsg" ng-change="updateChatMsg(chatMsg)" placeholder="Chat message"></textarea>
<div>{{ chatMsg }}</div>
</div>
</form>
What I'm trying to achieve: a user types some text in the textarea => $scope.chatMsg gets the value of the textarea. Now the user press one of the button's => the name of the button is added to the latest cursor position. (it's no problem to find the latest cursor position)
The problem
There is a difference between the value of $scope.chatMsg, {{ chatMsg }} inside the div and the text in the textarea.
The contents of the textarea and the div stays always the same. But when pressing the button the name is added to $scope.chatMsg but the contents of the textarea isn't changed...
How can I solve this?
TIA
First of all, you're mixing jQuery with AngularJS, it doesn't look like you need jQuery here that much.
Also, your chat message is updated in 3 different functions, so you need some debugging to see which are fired.
In general:
To solve your issue, try some more debugging, do a
$scope.$watch($scope.chatMsg, function(){
console.log($scope.chatMsg);
});
this will watch all changes to chatMsg. Add console.log() to each of your functions and you can watch which is fired.
Also, rather than using {{ }} inside your div just use ng-bind since that text is the only item in your div, it's cleaner if your app crashes somewhere.
// change from
<div>{{ chatMsg }}</div>
// to
<div ng-bind="chatMsg "></div>
Update: after seeing your plunker, I modified it and came up with this: http://plnkr.co/edit/oNKGxRrcweiJafKCm9A5?p=preview
Your ng-repeat needs to be tracked by $index so that duplicates are displayed rather than crashing when someone creates the same message
I solved all problems. The plunkr form above works. So after investigating all scopes with the Angular chrome extension I saw that chatMsg was defined in another scope. Thus not in the scope I was trying to acces it from.
Via this question angularJS ng-model input type number to rootScope not updating I found a solution.
I added chatMsg to the fields object.

Pass object to template and render it on current view

There is a list of users loaded from an api
<div ng:controller="UserController">
<li ng-repeat="user in users">
<a ng:click="select(user)">
{{user.first_name}} {{user.last_name}}
</a>
</li>
</div>
When a user is clicked I want to open an extra view that shows some detailed information of the user. Imagine the view like this
The small blue area is the selected user and the big blue area the container that shows detailed user information.
function UserController($scope){
$scope.select = function(user){
console.log(user);
}
}
So when the user is clicked I can log the user object. It works until this point. But I absolutely have no idea how to open the extra container filled with user data.
Is there a way to simply load a template from file system, pass the object and append the whole thing to the current view? How would I do this with angular.js?
No need to load templates or anything. Just put the data in the scope, and use expressions in the big blue section that reference the data. Angular will handle changing the displayed content when the selection is changed. You can hide the relevant section with ng-show until the data get selected.
Here's a fiddle example.
function UserController($scope){
$scope.users = [{name:'me',email:'mine'}, {name:'you',email:'yours'}];
$scope.selectedUser = null;
$scope.select = function(user){
$scope.selectedUser = user;
}
}
and
<div ng-controller="UserController">
<button class="btn" ng-click="select(users[0])">User 1</button>
<button class="btn" ng-click="select(users[1])">User 2</button>
<hr>
<div ng-show="selectedUser != null">
<div>{{selectedUser.name}}</div>
<div>{{selectedUser.email}}</div>
</div>
You could highlight the corresponding small blue box with a similar ng-class or ng-style attribute (e.g. ng-class="{active: selectedUser == user}"). See What is the best way to conditionally apply a class?

Resources