How to access the username out of a ng-repeat - javascript

I have a list of users generated with ng-repeat and data from db, which works fine. Now when you click on a user, you get a popup box. I would like to display the name of the selected user in this popup box, but I don't know how to access the username because the ng-repeat does not take place in the popup box.
Note that I work with angular material
Part of my html code:
<!-- START SIDEBAR -->
<div id="logo-wrap">
<img id="logo" src="assets/images/logo2.png" alt="Zazzle Logo" >
</div>
<div id="sidebar" class="md-whiteframe-z4" ng-data-color="">
<div style="height: 80px;"></div>
<div class="userList" id="usrL">
<li id="customLI" ng-repeat="user in users" id="userPos" class="active circular md-whiteframe-z2" style="background-color: {{ user.color }} " ng-click="showPopUpDeletionConfirmation($event, user._id); " ng-data-id="{{ user._id }}">
<div ng-if="user._id==activeUser" class="wrapperImageCurrentUser" id="marker_active_user"> </div>
<p class="initials" id="userValue" style="top: {{ user.top }};" >
<custom id="user._id"></custom>
{{user.initials}}
<!-- {{user.email}} -->
</p>
<md-tooltip>{{user.name}}</md-tooltip>
</li>
</div>
</div>
<!-- END SIDEBAR -->
The code for the popup box (html) resides in the file dialog1.tmpl. This file is just the layout of the popup box nothing relevant to share the code in this question
Here is a visual of my user list and popup box -> https://gyazo.com/694f65c5269cbca910ec6989ee5a77c2

You don't access the user in the popup, you pass the user to the popup.
You are already sending the users id, just send the entire user. Use user.name and user._id after you've send it.

Change this:
ng-click="showPopUpDeletionConfirmation($event, user._id);"
to this:
ng-click="showPopUpDeletionConfirmation($event, user);"
and access user object in the popup
EDIT:
You need also to change the showPopUpDeletionConfirmation with this:
$scope.showPopUpDeletionConfirmation = function (ev, user) {
$mdDialog.show({
controller: 'DialogDeleteUserController',
templateUrl: 'confirmDeletion.tmpl.html',
//parent: angular.element(document.body),
locals: {
userId: user._id,
selectedUser: user.name,
},
targetEvent: ev,
hasBackdrop: false,
})
.then(function (result) {
if (result) {
$scope.users = _.filter($scope.users, function (user) {
return user._id !== userId;
})
}
});
}
And then you can access the entire user object in the popup template with $scope.selectedUser or something like {{selectedUser.name}}

Related

AngularJs Filter: Generating notArray errors

I'm having an issue with a filter in my angularJS project.
We have a simple draft feature that allows users to save the contents of a large form as a JSON string in our database. They then can go to a section of the site to display and continue working on these forms. I want to provide them a filter on that page to filter by the date they saved the draft on.
Here is my markup:
<div ng-controller="savedFormCtrl" ng-cloak id="saved-form-wrapper"
class="border border-dark border-top-0 border-right-1 border-bottom-1
border-left-1 px-0" ng-init="getSavedForms()"
>
<!-- Search filters -->
<form name="savedFormsFilterWrapper" layout="row" flex="35" layout-align="end center" class="toolbar-search">
<!-- Date filter -->
<md-input-container flex="80">
<div class="text-light font-weight-bold float-left">Filter by saved date:</div>
<md-tooltip style="font-size:1em;">Filter your saved HRTF's</md-tooltip>
<md-datepicker name="dateFilter" class="hrtf-date savedFilterDatepicker"
md-date-locale="myLocale" data-ng-model="savedFormFilters" ng-blur="setFilterDate()"
md-placeholder="" md-open-on-focus
aria-label="Saved forms date filter">
</md-datepicker>
</md-input-container>
</form>
<!-- Saved forms body -->
<div id="savedFormAcc" class="accordion col-md-12 pt-3">
<!-- Accordion item Header -->
<div class="card" ng-repeat="item in savedForms | filter:savedFormFilters">
<div class="card-header savedFormItem" id="savedForm{{$index}}" data-toggle="collapse" data-target="#collapse{{$index}}">
<md-button class="md-raised md-primary" data-toggle="collapse"
data-target="#collapse{{$index}}" aria-expanded="false"
aria-controls="collapse{{index}}"
>
Form Saved on {{ item.savedOn }} - Click to expand
</md-button>
</div>
<!-- Accordion body continues on below -->
</div>
</div>
And my JS:
(function () {
'use strict';
angular.module('hrtf')
.controller('savedFormCtrl', ['$scope', '$window', 'formService',
function savedFormCtrl($scope, $window, formService) {
$scope.savedFormFilters = '';
//Get users's saved forms
$scope.savedForms = {};
$scope.getSavedForms = function(){
formService.getSavedForms()
.then(saved => {
saved.forEach( item =>{
item.data_json = JSON.parse(item.data_json);
});
$scope.savedForms = saved;
return $scope.savedForms;
};
}
]);
})();
Now, the filter works. But whenever The page is loaded, anywhere from 20-50 errors appear, all with the contents Error: [filter:notarray] Expected array but received: {}
All I need to do here is provide a simple filter on a string value to the parent objects savedOn: xxData Herexx value.
What am I doing wrong?
Turns out, I had a similar issue to this post
Basically, my ng-repeat and filter were initializing before the associated model could load. Initializing the model as a blank array and then creating the filter as part of the promise chain did the trick:
//Get users's saved forms
$scope.savedForms = [];
$scope.getSavedForms = function(){
formService.getSavedForms()
.then(saved => {
//Convert and format items here
$scope.savedForms = saved;
$scope.savedFormFilters = { savedOn: ''};
return $scope.savedForms;
}).catch(e => { console.error(e);
});
};
Pretty basic, but I'll leave it here in case it helps someone in the future :)

Angular HTTP request follow link to another endpoint

I am using ng-repeat to print a list of posts to the page via the WordPress REST-API. I am using Advanced Custom Fields on each post. From what I can see everything is working, but the post data is not showing in one container, yet it is displaying in another. I should also mention that this is set up like tabs. (user clicks a tab for a post and it displays that posts data)
Here is the code:
var homeApp = angular.module('homeCharacters', ['ngSanitize']);
homeApp.controller('characters', function($scope, $http) {
$scope.myData = {
tab: 0
}; //set default tab
$http.get("http://bigbluecomics.dev/wp-json/posts?type=character").then(function(response) {
$scope.myData.data = response.data;
});
});
homeApp.filter('toTrusted', ['$sce',
function($sce) {
return function(text) {
return $sce.trustAsHtml(text);
};
}
]);
HTML:
<section class="characters" ng-app="homeCharacters" ng-controller="characters as myData">
<div class="char_copy">
<h3>Meet the Characters</h3>
<div ng-repeat="item in myData.data" ng-bind-html="item.content | toTrusted" ng-show="myData.tab === item.menu_order">
<!--this is the section that will not display-->
<h3>{{ item.acf.team }}</h3>
<h2>{{ item.acf.characters_name }} <span>[{{item.acf.real_name}}]</span></h2>
<p class="hero_type">{{ item.acf.hero_type }}</p>
{{ item.acf.description }}
Learn More
</div>
</div>
<div class="char_tabs">
<!--if I put the identical {{}} in this section it WILL display-->
<nav>
<ul ng-init="myData.tab = 0" ng-model='clicked'>
<li class="tab" ng-repeat="item in myData.data" ng-class="{'active' : item.menu_order == myData.tab}">
<a href ng-click="myData.tab = item.menu_order">
<img src="{{ item.featured_image.source }}" />
<h3>{{ item.title }}</h3>
</a>
</li>
</ul>
</nav>
</div>
</section>
I should also mention that I use Ng-inspector, and it does show the data being pulled in. I can confirm this via the console. I have checked to ensure no css is in play; the div is totally empty in the DOM.
I appreciate all the help the GREAT angular community has shown!

Template is looping through users collection when autopublish is removed

I've written code for a website which allows you to login and chat with other users. The root page has a list of the users you can chat to. Here's the code:
<!-- Top level template for the lobby page -->
<template name="lobby_page">
{{> available_user_list}}
</template>
<!-- display a list of users -->
<template name="available_user_list">
<h2 class="cha_heading">Choose someone to chat with:</h2>
<div class="row">
{{#each users}}
{{> available_user}}
{{/each}}
</div>
</template>
<!-- display an individual user -->
<template name="available_user">
<div class="col-md-2">
<div class="user_avatar">
{{#if isMyUser _id}}
<div class="bg-success">
{{> avatar user=this shape="circle"}}
<div class="user_name">{{getUsername _id}} (YOU)</div>
</div>
{{else}}
<a href="/chat/{{_id}}">
{{> avatar user=this shape="circle"}}
<div class="user_name">{{getUsername _id}}</div>
</a>
{{/if}}
</div>
</div>
</template>
and the helper functions:
Template.available_user_list.helpers({
users:function(){
return Meteor.users.find();
}
})
Template.available_user.helpers({
getUsername:function(userId){
user = Meteor.users.findOne({_id:userId});
return user.username;
},
isMyUser:function(userId){
if (userId == Meteor.userId()){
return true;
}
else {
return false;
}
}
})
I've written publish/subscribe code for Chats collection but that's for when you click on one of the users and sends them a message. Now that I've removed autopublish, in the root page, the user can't see any other users to click on. Can someone please help with this issue?
Meteor.users will only publish the current users profile if autopublish is removed.
Add the below publish to your server code:
Meteor.publish(null, function () {
if (!this.userId) return this.ready();
return Meteor.users.find({});
});
A null publish will be auto-published and auto-subscribed by the client if autopublish is removed.
Also, remember to include only those fields that are not sensitive. For, Eg. you might want to omit the password field or the services field.
Something like this:
Meteor.users.find({}, {
fields: {
profile : 1,
emails : 1
}
});

Compile an html template with data from my controller

In Angular,I am building a web app for an hotel that has different rooms. I want to be able to click on a tab in the navbar (or anywhere on the page.) and populate the html view with public data about the room that I have stored in the controller.
what is the best way to go about this? I am using ui-routing. I have yet to find an exhaustive answer on stack overflow.
Below is an example of what my app looks like.
This is my app.js
var appBB = angular
.module('appBB', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', MainRouter]);
function MainRouter(states, router) {
states
.state( 'home', {
url:'/',
templateUrl: 'home.html'
}).state( 'show',{
url:'/show',
templateUrl:'show.html'
});
router.otherwise('/');
}
This is my controller
appBB.controller("BBController", BBController());
function BBController() {
var self = this;
self.apartments = [
{
name: "apt1",
image: "imag1.jpg"
amenities: ["blablabal", "bhuhuih", "hvjf"]
},
{
name: "apt2",
image: "img2.jpg",
amenities: ["blablabla", "bkjhkg", "lkhug"]
},
{
name: "apt3",
image: "img3.jpg",
amenities: ["blablabla", "jgfkhgc","jgvkhg"]
}
]
}
This is an example of the view template that I want to fill:
<div ng-controller="BBController as bbs">
<div>
<h4>{{this should show the apt name}}</h4>
</div>
<div class="row">
<div class="col-sm-8">
<img ng-src="{{this should show the image of the apt that i clicked on}}" />
</div>
<div class="col-sm-4">
<ul>
<li ng-repeat="looping over the apt amenities">{{amenity}}</li> </ul>
</div>
</div>
</div>
Any help will be greatly appreciated.
What you are doing looks good but you need some improvement in it.I would suggest you to use $routeParams on Nav-bar clicks. something like:
<div ng-controller="BBController as bbs">
<div>
<h4>{{this should show the apt name}}</h4>
</div>
<div class="row">
<div class="col-sm-8">
<img ng-src="{{this should show the image of the apt that i clicked on}}" />
</div>
<div class="col-sm-4">
<ul>
<li ng-repeat="amemity in amenities">
<a ng-href="#amemityList/{{ amemity.id }}"> {{amemity.name}} </a>
</li>
</ul>
</div>
</div>
Now, you can use this amenity.id to pass to YourController and accordingly fetch respective view with all the info of that "clicked" amenity.id
.when('/amemityList/:navBar', {
templateUrl: "AmenityView.html",
controller: "YourController"
})
In this way, you will be able to use single view AmenityView.html and its info can be as per your amenity.id which has been passed to the controller like
var navBarSelection_id = $routeParams.navBar;
Maybe, you could add the info at the url like /show/apt1 and use apt1 to find the information on the controller.
Edit:
A little explanation: https://docs.angularjs.org/tutorial/step_07

MVC display partial view on navigation bar click

I want to display the partial view, when I click on navigation bar click. I have a view which contains left side menu. when user click on navigation bar item, appropriate view should display.
I am not getting how can I implement such view?
Manage.cshtml
<div class="row">
<div class="col-xs-12">
<div class="page-header">
<h1>My Account</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-3">
<ul class="nav nav-pills nav-stacked nav-stacked-extended">
<li class="active">
<a id="A3" target="_self" runat="server" href="#Url.Action("Contactinfo", "Account")">Contact Info</a>
</li>
<li class="">
<a id="A4" target="_self" runat="server" href="#Url.Action("changePassword", "Account")">Password</a>
</li>
</ul>
</div>
<div class="col-xs-9 ng-scope" data-ng-view="">
<div class="row row-gap-medium ng-scope">
#Html.Partial("Contactinfo")
</div>
</div>
</div>
In above code, I have created left side menu i.e contactinfo, changepassword etc. when Manage.cshtml load first time I want to display Contactinfo view. When user click on password menu, contactinfo get's changed with changedpassword page. Please check following screen shot.
Here in above image you can see left side menu and appropriate page. What I want when user click on password, view changed to password page. Currently it shows contact info page. How can I do this?
i think you should render partial through JavaScript.
Let's say you have <div id="partialView"></div>
Then you should run Ajax query when user clicked on link.
Something like:
$.ajax({
url: $(this).data('yourUrl'),
type: 'GET',
cache: false,
success: function(result) {
$('#partialView').html(result);
}
});
Took me a little while to figure this out too.
Essentially, you want your Controller action to return a partial view, then use Ajax to load that returned partial view.
JavaScript / Ajax
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: 'POST',
data: { 'viewName': 'password' },
success: function (data) {
$('#partial-container').html(data);
}
});
Controller return type
Public ActionResult GetView(string viewName)
{
return PartialView(viewName, model);
}
Ideally, change your HTML so it's easier to reference the div container where you'd like to load the partial
<div class="col-xs-9 ng-scope" data-ng-view="">
<div class="row row-gap-medium ng-scope">
<div id="partial-container">#Html.Partial("Contactinfo")</div>
</div>
</div>
In your requirement just make partial Views of the links present in your left side bar and when user clicks on a specific option in left side bar then just load a appropriate partial view from ajax call using jquery and just replace html of right side bar with the html coming from ajax call.
Give your left side menues unique id and then :
A Demo :
$(document).ready(function(){
$("#menu1").click(function(e){
e.preventDefault();
$.ajax({
url: "/MyController/getdata",
type: 'GET',
datatype: 'html',
data: { },
success: function (data) {
$("#div1").html('');
$("#div1").html(data);
});
});
});
Controller(MyController) :
[HttpGet]
Public ActionResult getdata(string dropval)
{
//bind model here
return PartialView("mypartialview",model)
}
try This JS for Clickevent
$(document).on('click', '#anCalcBtn', function () {
$('#anCalcDetail').load('/Home/Contactinfo/');
});
If I am not wrong you are trying to do like This

Categories

Resources