Accessing JSON array values in a nested controller in AngularJS can be achieved by using

How can I access a Json array value in another controller? I am working with nested controllers where the nested controller should return the first character of the first name and last name.

For example, if my first name is Anand Jee, it should return AJ. If the name is Rohan Kumar, it should return RK.

Here is my AngularJS code:

//create module
var myApp = angular.module("myApp", []);

//create controller

myApp.controller("empCtrl", function ($scope) {
    var Employees = [
        { FirstName: "Anand", LastName: "Jee", Roles: "Web Developer", Technology: ".NET" },
        { FirstName: "Pritus", LastName: "Dubey", Roles: "Window App Developer", Technology: "XAMARIN" },
        { FirstName: "Vineet", LastName: "Rai", Roles: "Web Developer", Technology: ".NET" },
        { FirstName: "Nilesh", LastName: "Pathak", Roles: "UI/UX Developer", Technology: "Photoshop" },
        { FirstName: "Vikesh", LastName: "Juyal", Roles: "Web Developer", Technology: "PHP" }
    ];
    $scope.Employees = Employees;
});

myApp.controller("EmpShortName", function ($scope) {
    $scope.getEmpShortName = function () {

        //$scope.empShortName  = $scope.Employees.FirstName + " " + $scope.Employees.LastName;//here is problem
        $scope.empShortName = "NP";//For temporary declaration
        return $scope.empShortName;
    };
});

Check out the PLUNKER DEMO

Answer №1

Inject the Employee object into the getEmpShortName function. Then simply return the parsed value. Additionally, you can eliminate the need for the EmpShortName controller by placing the scope function within your empCtrl controller:

HTML:

<div class="empTextImage">{{getEmpShortName(emp)}}</div>

JS:

$scope.getEmpShortName = function (emp) {
    return emp.FirstName.substr(0,1) + emp.LastName.substr(0,1);
};

View Updated Plunker

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my for loop to become unresponsive?

My for loop seems to be populating all fields with the last object parsed. http://codepen.io/anon/pen/EKxNaN This is my current code. I created something similar on CodePen since I can't access JSON from the original source there. var championMaste ...

Getting started with Preact.js: Setting up an auto re-run server similar to React.js

Is there a way to set up a development server for Preact similar to how React operates with npm start? Currently, when I use the same command with Preact, it launches a static server and requires manual restart each time I make changes to my project. Here ...

Looking for guidance on writing a JASMINE test case for my method. I've been struggling to mock the event listener. Can you please direct me to a relevant link or share some mock examples

Looking to create a jasmine test for the code snippet below... refreshCacheIfNewVersionIsAvailable(); //Function to check for a new cache version on page load and refresh the app cache if newer files are available function refreshCacheIfNewVersionIsAvail ...

Guide on extracting Nolhmann JSON objects and converting them into individual strings

I'm in the process of converting my json object, which contains data from a .json file, into strings. I am utilizing the nolhmann json dictionary library for this task. Below is the content of the .json file: "dictionary": [ {"word": "MEAGRE", "d ...

Displaying all items in a collection as HTML using Node.js

I am looking to showcase all the items in my mongodb collection as HTML. In the past, I have accomplished this with simpler tasks, such as... router.get('/', function (req, res) { res.render('home', { title: 'Express', u ...

Using a for loop to showcase data in Timeline component of Material-UI in React

I have a JSON data that looks like this: [ { "module_id": 2, "module_type": "Instructional", "module_name": "Introduction and Course Overview", "duration": 30, ...

Converting dates in Javascript

I have retrieved a date/time value of "20131218" from an API response. My goal is to transform this date into the format "2013-12-18". In PHP, this can be easily achieved with the following code: echo date("Y-m-d", strtotime('20131218')); The ...

Obtain the Foursquare access_token through a PHP cURL request

I'm currently testing a cURL function to retrieve the access token for a specific user on Foursquare. The given function displays the access token in JSON format. {"access_token":"5B25GW5LF3L4W04PALHK32X5Z3YGNUUVDHM2TFBQOWZSQ121"} However, I am enco ...

What is the reason behind the varying display of values?

When trying to set a value using the input tag, I encountered an issue. For example, if I type 1000.0009 into the input text, the valid value should be 1000.0001. However, the value displayed in the input tag is incorrect, while the value outside the tag i ...

The prefixes for Ruby on Rails routes are not properly preprocessed in the .erb.js file

I'm currently working with Rails 4 and encountering an issue with the following file: // apps/assets/javascripts/products.js.erb var getColoursAndMaterialsData = function(onSuccess) { var fd = formdata(); $.post( '<%= data_products_ ...

What methods can I use to prevent a number from becoming negative?

I am currently developing a game where players collect resources, spend them to create more resources, and engage in various activities. However, I'm facing an issue where the resource count goes into negative numbers when too much of a certain item i ...

Creating an expandable discussion area (part II)

After checking out this query that was posted earlier, I am interested in implementing a similar feature using AJAX to load the comment box without having to refresh the entire page. My platform of choice is Google App Engine with Python as the primary lan ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

Multer failing to generate file during request process

My current setup involves a router and multer middleware, but I'm facing an issue where the file requested is not being created. As a result, req.file always remains undefined. const multer = require('multer'); let storage = multe ...

Looking for a bootstrap table code that includes checkboxes and a save button, so that when the save button is clicked, it

Seeking a Bootstrap table code that includes row checkboxes. When the save button is clicked, it should return the selected checkbox rows. ...

The Ajax success callback unexpectedly displays the number "1" in the top left corner of the empty page instead of updating the specified div

Currently, I am in the process of developing a Yii2 application. I have encountered an issue where I select data from a Bootstrap modal popup and submit it to a controller action that contains an insert query. The problem arises after submitting the data f ...

Enhancing Data Tables with Jquery: Implementing Column Filtering for Multiple Elements within Table Cells

I am looking to utilize jQuery datatables for filtering a column that may contain multiple values within a single td. To achieve this, I referenced the example provided in the datatables documentation. In the image below, my goal is to filter the office ...

Classify the JavaScript objects according to the array of object lists

Struggling to find a solution for converting this list of objects based on the group array. The challenge lies in iterating through the group Array and applying the object to multiple places when there are several groups. Additionally, trying to disregard ...

How to access v-for dynamically generated elements beyond the loop

How can I access a dynamically created item outside of a v-for loop in Vue.js? <li v-for="item in cart.items"> <h1>{{ item.product.name }}</h1> </li> <p>Is it possible to access {{ item.product.name }} out ...

What is the method for including as: :json in your code?

I have a file with the extension .ts, which is part of a Ruby on Rails application. The code in this file looks something like this: export const create = async (params: CreateRequest): Promise<XYZ> => { const response = await request<XYZ> ...