how to change the content of a single div in ng-repeat - javascript

I have this angular code.
<div ng-repeat="item in items | filter:search" class="container">
<h3>{{item.name}}</h3>
<p>category:{{item.category}}</p>
<p>price:INR {{item.price}} /-</p>
<br/>
<button ng-hide="showme" ng-click="process(item.name,item.price)">Add</button>
<button ng-show="showme" class="ng-cloak">Remove</button>
</div>``
Now what I want is whenever I click on the add button in one the div that button should hide and a remove button should display. I am able to do that but all the div are changing. I want to change just that div for which the button is clicked.
Here's my controller code
var myApp = angular.module('myApp',[]);
myApp.controller('restaurantController', function($scope, $http){
$http.get('apna.json').success(function (data){
$scope.items = data;
});
$scope.showme=false;
$scope.process = function(name,value){
$scope.total = parseInt($scope.total) + parseInt(value);
$scope.showme = true;
}
});

you can assign a showme field to your items array , and give it a value to false , and in the ng-show and ng-hide directive use item.showme . Similarly in process() change the showme variable related to that item

Your showme variable is on $scope, so each item does not get a new showme variable/property to hold its individual setting. So instead of putting it on $scope you can just set a new property on item itself indicating wither or not it was added. You then use that to test in your ng-show/hide.
<button ng-hide="item.added" ng-click="process(item)">Add</button>
<button ng-show="item.added" class="ng-cloak">Remove</button>
And in your process method
item.added = true;
Demo
var myApp = angular.module('myApp',[]);
myApp.controller('restaurantController', function($scope, $http){
$scope.items = [
{name:"Item 1",category:"food",price:19},
{name:"Item 2",category:"auto",price:39},
{name:"Item 3",category:"software",price:13}
];
$scope.total = 0;
$scope.process = function(item){
$scope.total = parseInt($scope.total) + parseInt(item.price);
item.added = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="restaurantController">
Total: {{total}}<br>
<div ng-repeat="item in items | filter:search" class="container">
<h3>{{item.name}}</h3>
<p>category:{{item.category}}</p>
<p>price:INR {{item.price}} /-</p>
<br/>
<button ng-hide="item.added" ng-click="process(item)">Add</button>
<button ng-show="item.added" class="ng-cloak">Remove</button>
</div>
</div>

Related

tag box bind with angular js but not all value capture in id in javascript

app.controller("xyzController", ["$scope", "$location", "$window", "$http", function ($scope, $location, $window, $http) {
$scope.addTagList = [];
$scope.addTag = function () {
var branchid = $("#element").val();
var list = branchid.split("|");
var empid = list[0].trim();
var employee_name = list[1].trim();
$scope.addTagList.push({
empid: empid,
employee_name: employee_name,
});
}
$scope.RemoveAnswer = function (index) {
$scope.addTagList.splice(index, 1);
}
}]);
Today I am facing a problem like multiple tag box bind with angular js ng-repeat then tags show multiple in html but all tags wanted to hold in array in javascript variable but only get only first value get. And above code correctly running add and remove tags.
<input type="button" value="Add" class="form-control btn-sm btn-danger" ng-click="addTag()"/>
<div id="tags" style="margin: 6px;font-size:10px;" ng-repeat="item in addTagList" class="label label-danger"><span >{{item.empid}} | {{item.employee_name}} </span> | <a><span ng-click="RemoveAnswer($index)">X</span></a> </div> </div>
You can use ui-select for such select and tagging feature.
repo: https://github.com/angular-ui/ui-select
demo: http://angular-ui.github.io/ui-select/demo-tagging.html

Getting ID of the first item only on using ng-repeat

So here's my workflow-
I've got an HTML file in which a div tag is created on which I've placed ng-repeat which iterates and gives me a list of items. On this div tag, I've placed an ng-click function. On clicking and item in the div tag, a modal-popup is opened.
What I need is to pass the id of the item from ng-repeat and show the data of this id in the modal-popup.
Now I've written the code upto here and all things are working fine, but the issue that I'm facing is if I click on any of the items from ng-repeat the first item is only returned, and hence data for the id of the first item is only being displayed in the modal-popup.
How could I get the id of the particular item clicked (and not the first item) and pass it to the controller?
Here's my working code -
main HTML:
<div id="main">
<div ng-repeat="data in JsonData" ng-click="openModal()">
<div id="widget">
<div id="{{$index}}">
<div>
<h2 class="font-bold no-margins" id="{{data.itemName}}">
{{data.itemName}}
</h2>
</div>
<div>
// other code
</div>
</div>
</div>
</div>
</div>
main controller.js:
$scope.openModal = function () {
$rootScope.elementid = document.getElementById('main').getElementsByTagName('div')[2];
$rootScope.variableId = $scope.elementid.id; // This gives the value in {{$index}}
$rootScope.elementname = document.getElementById('main').getElementsByTagName('h2')[0];
$rootScope.variablename = $scope.elementname.id; // This gives the value in {{data.itemName}}
$uibModal.open({
templateUrl: 'url/to/modal/popup.html',
controller: 'PopUpController',
scope : $scope,
windowClass: "animated fadeIn",
backdrop:'static'
});
};
On doing inspect element, I found that the elements are getting their correct id.
This is for the {{itenName}} code: (names are coming correct)
h2#CorrectName.ng-binding
and this is for the {{$index}} code: (here, id is incrementing for the items of ng-repeat)
div#0.ng-binding
So where am I wrong here? Is it due to any asynchronous call? Or is it due to ng-binding (i.e id of the item is returned before the ng-binding function completes)?
I'm really stuck here for a couple of days now. Any help would be much appreciated. Thanks.
You should not get the HTML data, instead you should pass the values to your function
ng-click="openModal(data)"
and from that on you can get the data in your funtion
$scope.openModal = function (data) {
and now you can do with that data whatever you want
console.log(data.itemName)
angular.module('test', []).controller('test', function($scope) {
// Test data
$scope.JsonData = [{itemName: "Test"}, {itemName: "OtherTest"}];
$scope.openModal = function(data) {
// handling data
console.log(data);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="test">
<div ng-repeat="data in JsonData" ng-click="openModal(data)">
<div id="widget">
<div id="{{$index}}">
<div>
<h2 class="font-bold no-margins" id="{{data.itemName}}">
{{data.itemName}}
</h2>
</div>
</div>
</div>
</div>
</div>
you can pass your $index to ng-click="openModal()" , so it will be ng-click="openModal($index)" .
controller
$scope.openModal = function (id) {
console.log(id); // log the clicked id
}
you can pass selected JsonData object as parametr of openModal function
<div ng-repeat="data in JsonData" ng-click="openModal(data)">
also you can pass selected obj to modal controller
$scope.openModal = function (selectedObj) {
$uibModal.open({
templateUrl: 'url/to/modal/popup.html',
controller: 'PopUpController',
scope : $scope,
windowClass: "animated fadeIn",
backdrop:'static',
resolve : {
selected: function () {
return selectedObj;
}
}
});
};
and get selected obj in PopUpController
app.contoller('PopUpController',['selected', function(selected){
console.log(selected)
}])

How do I increment a counter when clicking an item in an ng-repeat?

I have generated a list with ng-repeat, where each item has a count variable. In each list item I have a link.
I want to increment the count when I click the link.
I tried the following way but it not work.
My Controller :-
myApp.controller('allpost', function ($scope, $http, $stateParams, Allposts) {
var id = $stateParams.id;
Allposts.GetAllposts(id).then(
function (response) {
$scope.allPosts = response.data.posts;
});
function ctrl($scope) {
$scope.increment = function(item){
item.count += 1;
}
}
})
and view like :-
<ion-content class="padding" lazy-scroll>
<div class="row no-padding HomeRowsList">
<div class="item itemfull" ng-repeat="post in allPosts">
<div class="item item-body">
<div>
<div class="title-news">
<div class="title" ng-bind-html="post.content"></div>
<div class="countbg">عدد المرات : {{post.custom_fields.azkarno}}</div>
<span>{{post.count}}</span><a onclick="ctrl(post);">Increment</a>
</div>
</div>
</div>
</div>
</div>
</ion-content>
In controller use
$scope.increment = function(item){
item.count += 1;
};
instead of
function ctrl($scope) {
$scope.increment = function(item){
item.count += 1;
}
}
and in html use
<span>{{post.count}}</span><a data-ng-click="increment(post)">Increment</a>
instead of
<span>{{post.count}}</span><a onclick="ctrl(post);">Increment</a>
It should be ng-click instead of onclick & the method name should be increment instead of ctrl.
Also remove unnecessary ctrl function wrapper from the increment method which is not needed at all, because whatever you wanted to call from the html should be included in the $scope of controller.
Markup
<span>{{post.count}}</span><a ng-click="increment(post);">Increment</a>

How to access data from multiple instances of the same child controller?

I have two types of controllers:
The first type of controller only appears once on an html page ("SingleChildController").
The second type of controller appears twice on the same page ("MultipleChildController") and is differentiated by the value of its property "instance".
Both of these are nested within my ParentController (see code below).
How can I access data from any of my 3 child controller instances in the ParentController?
I have tried adding two services, one for the SingleChildController and one for the MultipleChildController, but it seems like by doing so I am duplicating a lot of code. This is especially true in my actual code where each controller has many properties to monitor. Is there a better way to accomplish this?
EDIT: For further clarification, this view is for a form and I want to get all of my data back up into the ParentController so that I can submit my form.
(function() {
var app = angular.module('myApp', []);
app.controller('ParentController', ['$scope',
function($scope) {
var parent = this;
parent.singleName = "";
parent.multiple1Name = "";
parent.multiple2Name = "";
}
]);
app.controller('SingleChildController', ['$scope',
function($scope) {
var single = this;
single.name = "";
}
]);
app.controller('MultipleChildController', ['$scope',
function($scope) {
var multiple = this;
multiple.instance = "";
multiple.name = "";
}
]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ParentController as parent">
<!-- I would like these to show the data that was inputted below -->
ParentSingleName: {{parent.singleName}} <br />
ParentMultiple1Name: {{parent.multiple1Name}} <br />
ParentMultiple2Name: {{parent.multiple2Name}} <br /><br />
<div ng-controller="SingleChildController as single">
<input type="text" ng-model="single.name" />: {{single.name}}
</div>
<div ng-controller="MultipleChildController as multiple1" ng-init="multiple1.instance='first'">
<input type="text" ng-model="multiple1.name" />: {{multiple1.instance}} - {{multiple1.name}}
</div>
<div ng-controller="MultipleChildController as multiple2" ng-init="multiple2.instance='second'">
<input type="text" ng-model="multiple2.name" />: {{multiple2.instance}} - {{multiple2.name}}
</div>
</div>

Using angular to print out all the ids in an array one at a time along with a next button

I'm using Angular to repeat all these ids in an array but limit it to showing one at time like this:
<div ng-repeat="id in ids | limitTo:1">
{{array.id}}
</div>
I then want to have a div that when clicked will show the next id in the array, so basically increases the $index by one. Maybe something like...
<div ng-repeat="id in ids | limitTo:1">
{{array.id}}<br />
<div ng-click="$index + 1"></div>
</div>
The code above doesn't work so I can only surmise that I am going about this the wrong way. What's the right way to do this in Angular?
If you only want to show a single element at a time, there's no need to use an ng-repeat. You can just do something like this in your controller:
$scope.index = 0;
$scope.arr = ['your', 'array'];
$scope.increment = function() {
$scope.index = ($scope.index + 1) % $scope.arr.length;
};
And then in your view:
<div>
{{arr[$index].id}}<br />
<div ng-click="increment()"></div>
</div>
Well I think we cannot do that by increment $index as limitTo 1 says index is always zero
<button ng-click="onClick()">click here</button>
and onClick
$scope.onClick = function(){
//$index + 1
$scope.ids.shift();
}
Here is the plunker
http://plnkr.co/edit/A1VrbUoIPLhuA78CF4DM?p=preview
Demo FIDDLE
You only need to use ng-click and ng-init if you want to go through your ID array one by one:
In your view:
<div ng-controller="MyCtrl">
<button ng-click="index = index + 1" ng-init="index=0">
Next ID
</button>
ID: {{ids[index]}}
</div>
In your script file:
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.ids = [11, 21, 31, 41, 51]; //test array
}
Edit: you should also either disable the button when index >= arrayLength or reset the value of index to 0.

Categories

Resources