Binding to a transclude in AngularJS - javascript

I'm not confident what I'm trying to do is correct, so please give me a "more correct" option if the whole premise is wrong.
I have an AngularJS 1.5.11 application. I am trying to create a generic modal html tag that can be used throughout the application wherever a modal is required. I have a page template that looks like this:
<form class="page-sidebar-container" data-name="mainForm">
<div class="page-sections">
<div class="form-columned form-columned-1">
<div class="form-row">
<div class="section column column-0 span-0" id="section-JobFromType">
<h4 class="section-heading">From Type</h4>
<div class="columns gutters-large">
<div style="display: table;margin: 18px 0px;">
<api-select label="Type" items="fromTypeItems" item="selectedFromType" required>
</api-select>
</div>
</div>
</div>
<div class="section column column-1 span-0" id="section-JobToType">
<h4 class="section-heading">To Type</h4>
<div class="columns gutters-large">
<div style="display: table;margin: 18px 0px;">
<api-select label="Type" items="toTypeItems" item="selectedToType"
read-only="toTypeDisabled" required>
</api-select>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<api-modal is-open="entitySelectOpen" label="{{entitySelectLabel}}">
<modal-body>
{{$id}}
<api-select label="{{entitySelectParentLabel}}" items="entitySelectParentItems" item="selectedEntitySelectParent" required>
</api-select>
<api-select label="{{entitySelectChildLabel}}" items="entitySelectChildItems" item="selectedEntitySelectChild" read-only="entitySelectChildDisabled" required>
</api-select>
<api-select label="{{entitySelectEntityLabel}}" items="entitySelectEntityItems" item="selectedEntity" read-only="entitySelectEntityDisabled" required>
</api-select>
</modal-body>
<modal-actions>
{{$id}}
<api-button label="{{modalPrimaryActionLabel}}" type="primary" icon="icon-checkmark" on-click="modalPrimaryActionClick"></api-button>
<api-button label="Return" type="return" icon="icon-cancel" on-click="modalReturnActionClick"></api-button>
</modal-actions>
</api-modal>
with the following controller:
(function (angular) {
angular.module('views.jobcontrol', [
'ngRoute',
'components.formApiControlSelect',
'components.formApiControlText',
'components.formApiModal'
])
.config([
'$routeProvider',
function ($routeProvider) {
'use strict';
var route = {
templateUrl: 'modules/apiViews/jobcontrol/jobcontrol-view.html',
controller: 'JobControlController',
reloadOnSearch: false,
caseInsensitiveMatch: true
};
$routeProvider
.when('/view/jobcontrol/:action/:jobNumber/?', route);
}
]).controller('JobControlController', [
'$scope',
'$timeout',
'$routeParams',
function ($scope, $timeout, $routeParams) {
'use strict';
function generateMockGuid() {
var result, i, j;
result = '';
for (j = 0; j < 32; j++) {
if (j == 8 || j == 12 || j == 16 || j == 20)
result = result + '-';
i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
result = result + i;
}
return result;
function option(label,value){
return {
value:value,
label:label
}
}
$scope.fromTypeItems = [option("test",1)];
$scope.selectedFromType = null;
$scope.$watch('selectedFromType', function (){
console.log("do something");
});
/* to type */
$scope.fromTypeItems = [option("test",1)];
$scope.selectedToType = null;
$scope.toTypeDisabled = true;
$scope.$watch('selectedToType', function () {
console.log("do something else");
});
/* entity select modal */
$scope.selectedFromEntity = null;
$scope.selectedToEntity = null;
$scope.entitySelectParentItems = [option("parent 1", generateMockGuid()),option("parent 2", generateMockGuid()),option("parent 3", generateMockGuid())];
$scope.entitySelectChildItems = [option("child 1", generateMockGuid()),option("child 2", generateMockGuid()),option("child 3", generateMockGuid())];
$scope.entitySelectEntityItems = [option("entity 1", generateMockGuid()),option("entity 2", generateMockGuid()),option("entity 3", generateMockGuid())];
$scope.selectedEntity = null;
$scope.$watch('selectedEntity', function () {
console.log('selectedEntity has changed to ' + $scope.selectedEntity);
});
function clearModalSelections(){
console.log($scope);
$scope.selectedEntitySelectParent = null;
$scope.selectedEntitySelectChild = null;
$scope.selectedEntity = null;
}
$scope.modalPrimaryActionLabel = "Next";
$scope.modalPrimaryActionClick = function(){
clearModalSelections();
$scope.entitySelectOpen = false;
}
$scope.modalReturnActionClick = function(){
clearModalSelections();
$scope.entitySelectOpen = false;
}
}
]);
})(window.angular);
The modal works, it has my api-button's and api-select's in it, and the api-select's items are populated properly with the 3 options added to the $scope.entitySelectParentItems, $scope.entitySelectChildItems and $scope.entitySelectEntityItems arrays. The problem is that
$scope.$watch('selectedEntity', function () {
console.log('selectedEntity has changed to ' + $scope.selectedEntity);
});
never gets called. If I move the three api-select's out of the api-modal > modal-body and up the same level as the api-modal then everything works as expected (other than he elements being on the base page, rather than in the modal), but as soon as everything is inside the modal I lose access to when the user selects a value and what that value is.
I'm sure this must be something to do with the transclude having a seperate scope, but I'm confused. How can the api-select in the modal transclude access the main scope for its items to populate a select list and even updates if the list updates, but when the user selects something it isn't bound back to the scope the same way it does for the other api-select's on the page. Am I using ng-transclude wrong? Is this an OK thing to do, but I am missing a step?
In case it matters, the javascript for api-modal looks like this:
angular.module('components.formApiModal',[
'components.formApiButton'
])
.directive('apiModal', ['$timeout', '$compile', function ($timeout, $compile) {
'use strict';
return {
restrict: 'E',
templateUrl: 'modules/apiComponents/generic/modal/modal-template.html',
controller: 'apiModalController',
transclude: {
'body': 'modalBody',
'actions': 'modalActions'
},
scope: {
isOpen: "=",
label: '#',
actions: "="
},
link: function (scope, element, attrs) {
}
};
}])
.controller('apiModalController', ['$scope', function($scope) {
}]);
and the template:
<div class="modal-backdrop modal-large" data-ng-class="{'modal-closed' : !isOpen }">
<div class="modal-container">
<div class="modal" data-ng-click="$event.stopPropagation()">
<h1 class="modal-header" >{{label}}</h1>
<div class="modal-body">
<div class="form-messages" data-ng-if="formPage.overrideConfirmationMessages.length">
<div class="form-header-errors">
</div>
</div>
<h4 class="section-heading" data-ng-if="section.altHelp">{{section.altHelp}}</h4>
<div class="columns gutters-large">
<div ng-transclude="body"></div>
</div>
</div>
<div class="modal-footer" >
<div ng-transclude="actions"></div>
</div>
</div>
</div>
</div>

Related

AngularJS Html not updating with data change from factory

I started with this simple plunkr
From what I can tell it only uses one component. I have a project that uses multiple components. I have a cart and users clicks add button to add items to said cart. The check out component just empties the cart. I expect that when the cart is empty, the display also empties and the total would show 0.00, but that is not happening. From what I can tell the HTML only changes page load not on change of data and that is the problem, but it was my understanding that angular would take care of this on its own.
Thanks in advance
Relevant code:
app.config.js (this file has the factory and checkout functionality)
'use strict';
angular.
module('floorForceApp').
config(['$routeProvider', '$provide',
function config($routeProvider,$provide) {
$routeProvider.
when('/home', {
template: '<home-page></home-page>'
}).
when('/floors', {
template: '<floor-page></floor-page>'
}).
when('/cabinets', {
template: '<cabinet-page></cabinet-page>'
}).
when('/walls', {
template: '<wall-page></wall-page>'
}).
when('/checkout', {
template: '<checkout-page></checkout-page>'
}).
otherwise('/home');
},
]).factory('floorForceCart',function(){
let total = 0;
let addedItems = [];
// let additem = function(item,price){
// }
return{
addItems:function(item,count){
let exist =false;
$.each(addedItems,function(i,v){
if(v.itemNo === item.itemNo){
exist = true;
v.count = v.count + count;
total = total + (item.itemPrice*count);
}
});
if(!exist){
let toPush = {};
toPush.itemNo = item.itemNo;
toPush.count = count;
toPush.itemName = item.itemName;
toPush.itemPrice = item.itemPrice;
addedItems.push(toPush);
total = total + (item.itemPrice*count);
}
console.log("Cart:",addedItems);
console.log("Total:",total);
},
removeItems: function(item,count){
$.each(addedItems,function(i,v){
if(v.itemNo === item.itemNo){
v.count = v.count - count;
total = total - (item.itemPrice * count);
if(v.count == 0){
addedItems.splice(i,0);
}
}
});
},
getTotal:function(){
return total;
},
getCart:function(){
return addedItems;
},
checkout:function(){
total = 0;
addedItems = [];
console.log("Check out successful.");
console.log("Total:",total,"Cart:",addedItems);
alert("Checkout Successful!");
}
};
});
checkout-page.component.js (data is loaded from factory to here)
'use strict';
angular.
module('checkoutPage').
component('checkoutPage',{
templateUrl: 'checkout-page/checkout-page.template.html',
controller: function checkOutController($scope,$http,floorForceCart){
let self = this;
$scope.total = floorForceCart.getTotal();
$scope.cart = floorForceCart.getCart();
$scope.checkOut = function(){
floorForceCart.checkout();
}
}
})
checkout-page.html (this page displays the checkout)
<div>
<div style="height:30em;">
<div class="container-fluid h-100">
<div class="row h-100">
<div class="col-sm-4 h-100 ">
<div class="row prodImage h-100"></div>
</div>
<div class="col-sm-8 h-100 ">
<div class="row h-100">
<div class="checkOutTitleDiv titleDiv">Checkout</div>
<div class="checkOutCartDiv paddingZero">
<div ng-repeat="item in cart" class="row marginAuto cartItemRow">
<div class="itemNameDiv col-sm-5">{{item.itemName}}</div>
<div class="itemPriceDiv col-sm-3">{{item.itemPrice|currency}}</div>
<div class="itemQuantityDiv col-sm-4">
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4 itemQuantity">{{item.count}}</div>
<div class="col-sm-4"></div>
</div>
</div>
</div>
</div>
<div class="checkOutButtonDiv paddingZero">
<div class="row h-100 marginAuto">
<div class="col-sm-4 cartTotalDiv">
<div class="">Total:{{total|currency}}</div>
</div>
<div class="col-sm-4"></div>
<div class="col-sm-4">
<input class="checkOutButton btn btn-success" ng-click="checkOut()" type="button"value="Check Out"/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
It is because in the controller you add a property in the $scope referencing the same array of items referenced by the addedItems variable in the factory:
$scope.total = floorForceCart.getTotal();
$scope.cart = floorForceCart.getCart();
Then, when you call checkout from the factory, you re-assign the addedItems variable from the factory to a new array, and you assign a 0 to the total variable. The problem is that the properties $scope.total and $scope.cart doesn't have any way of knowing this. $scope.cart will still be pointing to the old array with items.
You could solve this by either:
Changing your $scope.checkOut to
$scope.checkOut = function(){
floorForceCart.checkout();
// And refresh your $scope
$scope.total = floorForceCart.getTotal();
$scope.cart = floorForceCart.getCart();
}
Or by instead of assigning a new array to addedItems in the factory, clearing it using:
addedItems.length = 0;
If you go with the last approach, you would still have to do $scope.total = floorForceCart.getTotal(); after floorForceCart.checkout(); to update the total in your $scope.

View not updating when splicing user from list in AngularJS

I have this problem in my app, when I use slice to remove the user from the list. However, it does not remove from the list. I am getting the user with a API url call. But for some reason, it does not remove the user from the list. Please, have a look at my code. If, you guys want the full code, I have put it in my github. I hope we both can solve this. Thank you in advance.
Here is my code:
<div ng-controller="MyCtrl">
<div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">
<a class="back" href="#/lawyer">Back</a>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>
<a class="delete" ng-click="confirmClick(); confirmedAction(person);" confirm-click>Confirm</a>
<div class="people-view">
<h2 class="name">{{person.firstName}}</h2>
<h2 class="name">{{person.lastName}}</h2>
<span class="title">{{person.email}}</span>
<span class="date">{{person.website}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
<br>
<b>Website:</b>
<input type="text" ng-model="person.website">
<br>
</fieldset>
</form>
</div>
</div>
</div>
App.js
var app = angular.module("Portal", ['ngRoute', 'ui.bootstrap' ]);
app.controller('MyCtrl', function($scope, $window) {
$scope.inactive = true;
$scope.confirmedAction = function (lawyer) {
$scope.$apply(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
});
};
});
app.directive('confirmClick', ['$q', 'dialogModal', function($q, dialogModal) {
return {
link: function (scope, element, attrs) {
// ngClick won't wait for our modal confirmation window to resolve,
// so we will grab the other values in the ngClick attribute, which
// will continue after the modal resolves.
// modify the confirmClick() action so we don't perform it again
// looks for either confirmClick() or confirmClick('are you sure?')
var ngClick = attrs.ngClick.replace('confirmClick()', 'true')
.replace('confirmClick(', 'confirmClick(true,');
// setup a confirmation action on the scope
scope.confirmClick = function(msg) {
// if the msg was set to true, then return it (this is a workaround to make our dialog work)
if (msg===true) {
return true;
}
// msg can be passed directly to confirmClick('Are you sure you want to confirm?')
// in ng-click
// or through the confirm-click attribute on the
// <a confirm-click="Are you sure you want to confirm?"></a>
msg = msg || attrs.confirmClick || 'Are you sure you want to confirm?';
// open a dialog modal, and then continue ngClick actions if it's confirmed
dialogModal(msg).result.then(function() {
scope.$eval(ngClick);
});
// return false to stop the current ng-click flow and wait for our modal answer
return false;
};
}
}
}])
/*
Modal confirmation dialog window with the UI Bootstrap Modal service.
This is a basic modal that can display a message with yes or no buttons.
It returns a promise that is resolved or rejected based on yes/no clicks.
The following settings can be passed:
message the message to pass to the modal body
title (optional) title for modal window
okButton text for YES button. set false to not include button
cancelButton text for NO button. ste false to not include button
*/
.service('dialogModal', ['$modal', function($modal) {
return function (message, title, okButton, cancelButton) {
// setup default values for buttons
// if a button value is set to false, then that button won't be included
cancelButton = cancelButton===false ? false : (cancelButton || 'No');
okButton = okButton ===false ? false : (okButton || 'Yes');
// setup the Controller to watch the click
var ModalInstanceCtrl = function ($scope, $modalInstance, settings) {
// add settings to scope
angular.extend($scope, settings);
// yes button clicked
$scope.ok = function () {
// alert("Lawyer is confirmed");
$modalInstance.close(true);
};
// no button clicked
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
// open modal and return the instance (which will resolve the promise on ok/cancel clicks)
var modalInstance = $modal.open({
template: '<div class="dialog-modal"> \
<div class="modal-header" ng-show="modalTitle"> \
<h3 class="modal-title">{{modalTitle}}</h3> \
</div> \
<div class="modal-body">{{modalBody}}</div> \
<div class="modal-footer"> \
<button class="btn btn-primary" ng-click="ok()" ng-show="okButton">{{okButton}}</button> \
<button class="btn btn-warning" ng-click="cancel()" ng-show="cancelButton">{{cancelButton}}</button> \
</div> \
</div>',
controller: ModalInstanceCtrl,
resolve: {
settings: function() {
return {
modalTitle: title,
modalBody: message,
okButton: okButton,
cancelButton: cancelButton
};
}
}
});
// return the modal instance
return modalInstance;
}
}])
app.config(function ($routeProvider) {
$routeProvider
.when("/lawyer", {
controller: "HomeController",
templateUrl: "partials/home.html"
})
.when("/lawyer/:id", {
controller: "LawyerController",
templateUrl: "partials/about.html"
})
.otherwise({
redirectTo: '/lawyer'
});
});
But the element is getting deleted from list right?
If yes then, Try this :
$scope.confirmedAction = function (lawyer) {
$scope.$apply(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
});
});
Or
$scope.confirmedAction = function (lawyer) {
$timeout(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$state.go($state.current, {}, {reload: true});
// $window.location.href = '#/lawyer';
},1100);
});
The problem is that you don't get the index from IndexOf when you using it on an array of objects like you do. Read more about the IndexOf here.
Instead, use map and then use IndexOf on that
Try it like this:
$scope.confirmedAction = function (lawyer) {
var index = $scope.userInfo.lawyers.map(function(e) { return e.id; }).indexOf(lawyer.id);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
};
And also, the controller changes will by default be detected by the digest loop of angular so no need to use $scope.$apply.
Also, simplifyed your plunker with the basic get array list and remove function. Use that to build your way forvered
https://plnkr.co/edit/w6NuVLcqzc5Rjs7L6Cox?p=preview

ngClass doesn't apply changes in parent directive

i made two directives, one's exposing an API for another directive using controller.
The child directive is a 'bodyElement' directive, and when clicked should update a class of the parent directive template.
While the modification of the parent $scope applies, the ngClass switch doesn't apply.
Hope you can help:
Directives:
.directive('humanBody', function () {
return {
transclude : true,
scope: {},
templateUrl: 'view1/template/human-body.tpl.html',
controller: ['$scope', function ($scope) {
$scope.form = {};
$scope.body = {};
$scope.body.selection = {};
$scope.body.selection.head = true;
$scope.body.selection.arm = false;
$scope.body.selection.chest = false;
$scope.body.selection.leg = false;
$scope.isActive = function (type) {
return $scope.body.selection[type];
};
this.toggle = function (type) {
$scope.body.selection[type] = !$scope.body.selection[type];
}
}]
}
})
.directive('bodyPart', function () {
return {
transclude : true,
scope: {
type: '#'
},
require: '^humanBody',
link: function (scope, elem, attr, humanBody) {
elem.on('click', function (event) {
console.info('toggle ' + scope.type);
humanBody.toggle(scope.type);
});
}
}
});
template of parent directive:
i need that isActive(type) in ngClass switch between no-background <-> type-container when toggling (false/true).
It just work when rendering the page.
<div class="container">
<div class="row col-xs-12 body-part-container body-container">
<div class="col-xs-12 "
ng-class="{'no-background': !isActive('head'), 'head-container':isActive('head')}">
<div class=" col-xs-12 arm-container"
ng-class="{'no-background': !isActive('arm'), 'arm-container':isActive('arm')}">
<div class="col-xs-12 chest-container"
ng-class="{'no-background': !isActive('chest'), 'chest-container':isActive('chest')}">
<div class="col-xs-12 leg-container container"
ng-class="{'no-background': !isActive('leg'), 'leg-container':isActive('leg')}">
<body-part type="head" class="head col-xs-12"></body-part>
<body-part type="arm" class="arm col-xs-4"></body-part>
<body-part type="chest" class="chest col-xs-4"></body-part>
<body-part type="arm" class="arm col-xs-4"></body-part>
<body-part type="leg" class="leg col-xs-12"></body-part>
</div>
</div>
</div>
</div>
</div>
</div>
You need to kick off digest cycle in bodyPart directive, as you are updating scope variable from customEvent(updating angular context from outside world wouldn't intimate angular to run digest cycle to update view level bindings).
Code
elem.on('click', function (event) {
console.info('toggle ' + scope.type);
humanBody.toggle(scope.type);
scope.$apply();
});

Tab Through Hidden Inputs in Angular

I'm looking for a way in angular to tab through hidden inputs. So I have multiple input forms but when not on focus I want them to just display the text. I'm looking for the ability to once I've selected an input to tab through the other inputs even though they are currently hidden.
Any suggestions?
Use Angular directives to make your inputs into inline editors. When the page loads you'll be in display mode (i.e. the display div will be shown and the editor div will be hidden), then on clicking, the mode switches to Edit mode and the visibility is reversed.
Here's a quick snippet of what a DatePicker control would look like when wrapped in such a directive. Using Angular 1 and Bootstrap 3 (follows John Papa's Angular Style Guide):
HTML Template (inlineDatePicker.html):
<div class="inline-edit">
<div ng-if="!vm.inEditMode" data-ng-click="vm.enableEditMode()">
<input type="hidden" data-ng-model="vm.dateModel" data-ng-required="vm.dateRequired" /><span>{{vm.dateModel}}</span> <span class="glyphicon glyphicon-calendar"></span>
</div>
<div ng-if="vm.inEditMode">
<div class="well well-sm" style="position: absolute; z-index: 10">
<datepicker data-ng-model="vm.dateModel" data-show-weeks="false"></datepicker>
<button type="button" class="btn btn-sm btn-info" ng-click="vm.today()">Today</button>
<button type="button" class="btn btn-sm btn-danger" ng-click="vm.cancel()">Cancel</button>
</div>
</div>
</div>
And the underlying directive (inlineDatePicker.directive.js):
(function () {
'use strict';
angular.module('myApp.inlineEdit')
.directive('inlineDatePicker', inlineDatePicker);
function inlineDatePicker() {
'use strict';
inlineDatePickerController.$inject = ['$scope', '$timeout'];
return {
restrict: 'A',
replace: true,
transclude: false,
templateUrl: '/App/inlineEdit/date/inlineDatePicker.html',
scope: {
dateModel: '=',
dateRequired: '#',
dateChanged: '&'
},
controller: inlineDatePickerController,
controllerAs: 'vm',
};
function inlineDatePickerController($scope, $timeout) {
/* jshint validthis:true */
var vm = this;
vm.inEditMode = false;
vm.dateModel = $scope.dateModel;
vm.dateRequired = $scope.$eval($scope.dateRequired);
vm.enableEditMode = enableEditMode;
vm.cancel = cancel;
vm.today = today;
function enableEditMode() {
vm.inEditMode = true;
}
function cancel() {
vm.inEditMode = false;
}
function today() {
vm.dateModel = new Date();
}
$scope.$watch('vm.dateModel', function (curr, orig) {
$scope.dateModel = vm.dateModel;
if (curr != orig && vm.inEditMode) {
$timeout($scope.dateChanged, 0);
}
vm.inEditMode = false;
});
$scope.$watch('dateModel', function () {
vm.dateModel = $scope.dateModel;
});
}
}
})();

How to access a key of an object by its variable name in DOM using angular

I have a controller which adds to scope a variable called comments
$scope.showComments = function(id){
dataService.getComments(id).then(function(data){
$scope.comments[id] = data.comments;
console.log($scope.comments);
});
}
I want to call the ng-repeat on a specific id. The following method is not working. Any ideas?
<div class="commentsContainer" id="{{id}}">
<div class="eachcomment" ng-repeat="comment in comments.{{id}}">
<p>{{comment.content}}
</div>
</div>
The desired id is given to the outer div. But ng-repeat is not working.
You should use a filter to achieve this functionality as follows:
<div class="eachcomment" ng-repeat="comment in comments | filterId: id">
<p>{{comment.content}}
</div>
Now, write a filter:
app.filter('filterId', function(){
return function(collection, id) {
var output = [];
angular.forEach(collection, function(item) {
if(item.id == id) {
output.push(item)
}
})
return output;
}
})
Or you can use an easier way:
<div class="eachcomment" ng-repeat="comment in comments | filter: checkId">
<p>{{comment.content}}
</div>
And in your controller:
$scope.checkId = function(item) {
if($scope.id == item.id) {
return true;
}
return false;
}
You can do that with:
<div ng-app="myApp" ng-controller="dummy">
<div class="commentsContainer" id="{{id}}">
<div class="eachcomment" ng-repeat="(key, comment) in comments">
<p ng-show="key === id">{{comment.content}}</p>
</div>
</div>
</div>
JS:
angular.module('myApp', [])
.controller('dummy', ['$scope', function ($scope) {
$scope.id = 0;
$scope.comments = [{
content: 'Hello'
}, {
content: 'World'
}];
}]);
JSFiddle
You should use bracket notation to access property by variable key:
<div class="commentsContainer" id="{{id}}">
<div class="eachcomment" ng-repeat="comment in comments[id]">
<p>{{comment.content}}
</div>
</div>

Categories

Resources