Utilizing controller variables within ng-repeat in AngularJS

As I delve into learning AngularJS, I am attempting to utilize a variable from the controller in an ng-repeat without using scope. However, my code is not functioning as expected. Can someone help me identify and correct my mistake? Below is the snippet of my code:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<select>
    <option ng-repeat="x in myCtrl.names">{{x}}</option>
</select>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    var that = this;
    that.names = ["Emil", "Tobias", "Linus"];
});
</script>
</body>
</html>

Answer №1

Assign the variable to the scope.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
     $scope.names = ["Emil", "Tobias", "Linus"];
});

Utilize the variable within the controller.

var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
    var self = this;
    self.names = ["Emil", "Tobias", "Linus"];
});
<script src="//unpkg.com/angular/angular.js"></script>

<div ng-app="myApp" ng-controller="myCtrl as myController">
    <select>
        <option ng-repeat="x in myController.names">{{x}}</option>
    </select>
</div>

Answer №2

Instead of directly using the controller name, it is recommended to use the alias specified with the 'as' keyword in the HTML code.

For instance:

var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
    var viewData = this;
    viewData.names = ["Emil", "Tobias", "Linus"];
});

<div ng-app="myApp" ng-controller="myCtrl as Ctrl">
    <select>
        <option ng-repeat="x in Ctrl.names">{{x}}</option>
    </select>
</div>

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

Toggle visibility of multiple DIVs with identical classes using radio buttons

I'm looking to streamline my use of radio buttons in HTML. How can I implement a single set of radio buttons at the top that will toggle the visibility of all DIVs with the same class on my webpage? <form> <input type="radio" name="csr_sel ...

Unexpected "<" and dual output in jade include seem to defy explanation

i am currently redesigning my website to incorporate dynamic includes. These includes are pre-rendered on the server and then passed to res.render() however, I am encountering unexpected occurrences of < and > on the page, along with the issue of th ...

Issue with SVG animation causing unnecessary duplication of circle shapes when utilizing animateMotion

I have implemented animateMotion to create an animation along a path. Below is the code snippet that demonstrates this: <!DOCTYPE html> <html> <head> <title>Example Of Many Things!</title> </head> <body> ...

What are the steps to modify the camera type in Three.js?

I have added a dropdown list on the page for selecting between two cameras - Perspective and Orthographic. Currently, my Three Scene is using a perspective Camera. I would like to dynamically change the camera to "Orthographic" when selected in the dropdow ...

Is it possible to declare variables using the "this" keyword?

Consider the scenario where this.x=5 is declared and assess the accessibility of all relevant places. <script> $(document).ready(function(){ $("button").click(function(){ this.x=!this.x; $("#div1").fadeTo(400,this.x ? 0.4 : 1); }); }); & ...

Utilize the bit manipulation technique on the elements of an array

Is there a preferred method for using the bitwise OR operator (or any other operator) on an array of values in JavaScript? var array = [1, 5, 18, 4]; // calculate 1 | 5 | 18 | 4 ...

Is there a way to select an element within a nested list item only when the preceding list item is clicked using Jquery/JavaScript?

I am working with an unordered list that looks like this: <ul> <li><a class="foo" id="one">some text</a></li> <li><a class="foo" id="two">some text</a></li> <li><a class="foo" id="thr ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

The primeVue menubar's active/focused item highlighting feature is not functioning correctly

Currently, we are in the process of developing an electron-based application with the front end primarily coded using Vue.js and primeVue. As a novice, I am encountering issues with the menubar component from primeVue. The problem is that no matter which i ...

Generate a new core element featuring the top 10 users

In my app, I have a function that sorts users in the mobile_user table based on their earned points and assigns them a rank. This function is triggered every time an http request is made. Now, what I want to achieve is creating a new root node called lead ...

Creating and downloading a Word document with Node.js by utilizing officegen

Recently, I've been trying to utilize the officegen npm module in order to generate a word (docx) file and then download it. Previously, I relied on the tempfile module to create a temporary path for the purpose of downloading. Below is the code snipp ...

Troubleshooting issues with AES decryption in crypto.js

When using crypto-js to decrypt data, I am encountering an issue where the result is blank despite having valid keys that work for online AES decryption. var CryptoJS = require("crypto-js"); var key = '+MbQeThVmYq3t6w9z$C&F)J@NcRfUjXn'; var ...

Steering clear of using relative paths for requiring modules in Node.js

When it comes to importing dependencies, I like to avoid using excessive relative filesystem navigation such as ../../../foo/bar. In my experience with front-end development, I have found that using RequireJS allows me to set a default base path for "abso ...

What is causing this error/bug to show up in Angular?

I encountered an error while working on my Angular project that incorporates both front-end and back-end development with Python Flask. Even though the page updates correctly, a database-related error is being displayed in the console. Below are the snippe ...

Using Firebase Firestore to fetch an array field from a particular document and then leveraging those array values for mapping other documents

In my database, I have user and group collections. Each document in the user collection corresponds to a user UID and contains an array field called "userGroups" which lists the groups that user belongs to, with each group being identified by the group&apo ...

Problem encountered during Step 2 of the AngularJS tutorial

Encountering an issue with the AngularJS tutorial step_02 on this specific URL: http://docs.angularjs.org/tutorial/step_02 I've successfully set up nodejs, karma, and jasmine on my Ubuntu 12.04 machine and can run unit tests without any problem. Howe ...

Ways to retrieve interface definition using a variable

I have an interface that organizes various states together export interface ScanFiltersStatePage1 { keywords: SensitiveInfoFileKeywordFilter categories: string[] classifications: string[] fileTypes: string[] infotypes: string[] regulations: str ...

Dealing with checked input type='checkbox' in React - A guide

Having a set of checkboxes, some already checked and some to be updated by the user. The issue here is that while the checkboxes render correctly initially, they do not change upon clicking. The 'checked' value does get updated when onChange is t ...

Is it recommended to place JavaScript/CSS at the bottom of an HTML document?

I am currently utilizing jQuery Mobile, and at the moment, my <head> section looks like this: <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1"> <title>help</title> <link ...

Morris.js is throwing an error message, stating "Uncaught TypeError: Unable to access the 'label' property as it

I have successfully implemented a bar chart along with a date picker using Bootstrap. The bar chart loads data accurately when selecting a specific day. However, upon inspecting the developer tools, I encounter the following errors: Uncaught Type Error: C ...