Is it possible to declare a variable without assigning a value to it immediately and instead assign a value later

I am facing an issue with assigning a value to a variable in my controller when a button is clicked. Here is the code snippet:

var app = angular.module('myApp', ['ngRoute']);    

....

var userArray = [
    {name: "John", age: 25}, {name: "Jim", age: 30}
];

app.controller('Page2Controller', function($scope) {
    $scope.message = 'Look! I am from page 2.';
    $scope.newArray = [];

    $scope.addUsers = function(){
        scope.newArray = userArray;

        console.log($scope.newArray);
    }  
}

app.config(function($routeProvider) {
    $routeProvider

    .when('/page2', {
       templateUrl : 'pages/page2.html',
       controller  : 'Page2Controller'

   ...

page2.html

<div>
     <p>{{ message }}</p>

     <ul>
         <li ng-repeat="user in Page2Controller.newArray">{{user.name}}</li>
     </ul>
</div>

index.html

<body ng-controller="MainController">
    <div id="sideMenu">
        <h2>Campaign</h2>

        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#page2">Page 2</a></li>
            <li><a href="#page3">Page 3</a></li>
            <li><a href="#page4">Page 4</a></li>
        </ul>
    </div>

    <div ng-view></div>
</body>

I'm confused as to why the $scope.user appears in the console but the "ng-repeat" doesn't display the users on the HTML page. Could it be that ng-repeat can't display data added dynamically?

Any assistance would be greatly appreciated.

Answer №1

Looks like that function was never called.

let app = angular.module('myApp', []);    
let userArray = [{name: "Sarah", age: 28}, {name: "Emily", age: 33}];
app.controller('Page3Controller', function($scope) {
    $scope.message = 'Hello from page 3.';
    // $scope.newArray = [];
    $scope.addUsers = function(){
        $scope.newArray = userArray;
        console.log($scope.newArray);
    }  
    $scope.addUsers();
});

Here's the HTML:

<div ng-controller="Page3Controller">
                         <p>{{ message }}</p>

                         <ul>
                             <li ng-repeat="user in newArray">{{user.name}}</li>
                         </ul>
                    </div>

I directly used your controller as I didn't set up ngRoute yet.

Answer №2

Consider changing to:

<li ng-repeat="person in scope.userArray">{{person.name}}</li>

It seems that 'Page2Controller' is not recognized in the template context.

Answer №3

To start, you will need an ng-click directive to trigger a function when clicked:

<button type="button" ng-click="asigningValue()"></button>

Next, in your Controller, define the function and assign the desired value:

app.controller('Page2Controller', function($scope) {
$scope.asigningValue = function() {
     $scope.message = 'Hello from page 2!';
  } 
}

Finally, display the assigned value using data binding in the directive:

<p ng-bind-html="message"></p>

I hope this explanation is useful!

Many thanks!

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

Is $resource causing $update to not be recognized as a function?

Need assistance with updating a document using two ids in my API root $resource("http://192.168.0.2:3060/product/:subid/:productid",{"subid": "@subid"},{"productid": "@productid"},{update:{method:"PUT"}}); Encountering an error stating: subproduct.$upda ...

Elements with absolute positioning are preventing drag events from executing

Struggling to create a slider and encountering an issue. The problem lies in absolute items blocking slider drag events. I need a solution that allows dragging the underlying image through absolute positioned items. Any ideas on how to achieve this? MANY T ...

Combining $var positions within a PHP loop

Currently, I have a PHP script that is assisting me in generating code for a script: <script> (function($){ <?php foreach($buttons as $button) { // Loop through all available buttons ?> // When button one is clicked $('.butto ...

Display an element with JSX using the .map() method only when a specific property of the source object is not null

<h1>Trending today</h1> <ul> {this.state.trendingMovies.map((movie) => ( <li key={movie.id}> <NavLink to={`/movies/${movie.id}`} className="movie-link"> {movie.title ? movie ...

The collapsible list feature that includes the use of plus and minus signs is malfunctioning

Below is the script that I wrote to address this issue, but for some reason the + and - swapping is not functioning correctly. $('.showCheckbox').click(function(e) { var dynamicBox = $(this).attr('val'); var collapseSign = $(th ...

Tips for repairing damaged HTML in React employ are:- Identify the issues

I've encountered a situation where I have HTML stored as a string. After subsetting the code, I end up with something like this: <div>loremlalal..<p>dsdM</p> - that's all How can I efficiently parse this HTML to get the correct ...

Looking to dynamically generate HTML tags using jQuery and JSON?

Looking for help with inserting HTML code into a div using jQuery. <div id="addme"></div> Here is some HTML with PHP: <div class="col-md-4 product secondproduct"> <div class="images1"> <a href="<?php echo base_u ...

Splitting AngularJS Controllers Into Individual Files

I'm currently utilizing Ui-Router in my AngularJS project and I'm seeking a way to organize my angular controllers into separate files for better organization. For instance: var app = angular.module('myApp', ["xeditable", 'ngRout ...

Saving a screenshot in a custom directory using Javascript Selenium

Is it possible to save a screenshot in a custom directory instead of the default root folder? Thank you ...

Having trouble retrieving a value from a .JSON file (likely related to a path issue)

My React component is connected to an API that returns data: class Item extends Component { constructor(props) { super(props); this.state = { output: {} } } componentDidMount() { fetch('http://localhost:3005/products/157963') ...

Mongoose does not support sorting with plain objects

I'm looking to retrieve a plain JavaScript object instead of a Mongoose object. Query chatModel.find({'userId':userId},{ "_id":0,"message":1,"type":1 }).sort({createdDateISO:-1}) .lean().exec((e ...

Executing the Javascript function specified above upon the page being loaded

I'm fairly new to JavaScript, so please bear with me. I've got a JavaScript function on my page: <script type="text/javascript"> Sys.debug = true; var popup; Sys.require(Sys.components.popup, function () { popup = Sys.c ...

Why isn't the CSS class being applied to the checkbox element?

I created a basic demo where the HTML markup was the same, but one extra rule was applied in one case and not in the other. Here is the Markup: <div class="rc40w1 oform oform-initialized"> <div class="rc40w5 hide"> < ...

Utilizing a dropdown selection to trigger an IF statement in a function

I have an HTML code snippet as shown below: The value "Test" is just for my reference to ensure that the code is functioning properly :) <script> var tfa78 = document.getElementById("tfa_78").selvalue; if( tfa78 == "karte" ) { document.getEl ...

Issue: Wed Nov 06 2019 19:50:56 GMT+0500 (Uzbekistan Standard Time) cannot be used as a React child

Just getting started with react and giving it a try, but I've hit a stumbling block. I wrote some JavaScript, however I keep encountering the mentioned error: class Content extends Component { constructor() { super(); this.date = {new Date ...

Can someone guide me on the process of assigning multiple classes in my situation?

Can someone assist me with combining multiple classes in an ng-class statement? I am attempting to utilize multiple classes for my element using ng-class. Here is what I have: <div id='test' ng-class="{blue: test, scale: scale, 'non-sca ...

What makes JSON in string form a legitimate string?

We all know that we can't use double quotes within double quotes: var str = ""hello""; //this will result in an invalid string However, when I stringify an object like this var obj = {"name":"abc"} var str = JSON.stringify(obj). str // outputs "{"n ...

Karma Jasmine: No executions and no errors detected

I recently started diving into Angular Testing using Karma and Jasmine. However, I encountered an issue after running karma init and creating my first test for a home controller - the result showed Executed 0 of 0 ERROR. It seems like the files are not bei ...

Expand the following number into its expanded form

I have been working on a code exercise that involves creating a function expandedForm to handle a number parameter. The examples provided below should help clarify the task at hand. expandedForm(12); // Should return '10 + 2' expandedForm(42); // ...

What is the best way to display a div box only when a user checks a checkbox for the first time out of a group of checkboxes, which could be 7 or more, and then hide the

Is there a way to make a div box appear when the user checks any of the first checkboxes? I have attempted using the following codes: JQ Codes: $('#checkbox').change(function() { if ($(this:first).is(':checked')) { cons ...