Populate the AngularJS scope with a dynamically generated array

My Angular Application is functioning properly with

  <script>
    var app = angular.module('MyApp', []);
    app.controller('myCtrl', function ($scope, $sce) {

          $scope.urls = [
            {
              "url": $sce.trustAsResourceUrl("https://www.youtube.com/watch?v=KhzGSHNhnbI")
            },
            {
              "url": $sce.trustAsResourceUrl("https://www.youtube.com/watch?v=OPxeCiy0RdY")
            }
          ]

    });
  </script>

However, it is encountering issues with:

  <script>
      urls = [
            {
              "url":"https://www.youtube.com/watch?v=KhzGSHNhnbI" 
            },
            {
              "url":"https://www.youtube.com/watch?v=OPxeCiy0RdY"          
            }
          ]
  </script>   

  <script>
    var app = angular.module('MyApp', []);
    app.controller('myCtrl', function ($scope, $sce) {

      function myUrl(url) {
          this.url = url;
      }

      $scope = [];
      urls.forEach(function (url, i) {

          $scope.push(new myUrl($sce.trustAsResourceUrl(url)));

      });

    });
  </script>

Update: the issue persists

 <script>
    var app = angular.module('MyApp', []);
    app.controller('myCtrl', function ($scope, $sce) {

        function myUrl(url) {
            this.url = url;
        }

        $scope.urls = [];
        urls.forEach(function (url, i) {

            $scope.urls.push(new myUrl($sce.trustAsResourceUrl(url)));

        });

    });
  </script>

Error: [$sce:itype] http://errors.angularjs.org/1.4.3/$sce/itype?p0=resourceUrl

Answer №1

modify

$scope.push(new myUrl($sce.trustAsResourceUrl(url)));
to
$scope.push(new myUrl($sce.trustAsResourceUrl(url.url)));

Click here to view the live demo.

 urls = [
            {
              "url":"https://www.youtube.com/watch?v=KhzGSHNhnbI" 
            },
            {
              "url":"https://www.youtube.com/watch?v=OPxeCiy0RdY"          
            }
          ]


var app = angular.module('plunker', []);
    app.controller('MainCtrl', function ($scope, $sce) {

      function myUrl(url) {
          this.url = url;
      }

      $scope.urls = [];
      urls.forEach(function (url, i) {

          $scope.urls.push(new myUrl($sce.trustAsResourceUrl(url.url)));

      });

    });
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f6f9f0e2fbf6e5b9fde4d7a6b9a5b9ef">[email protected]</a>" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p ng-repeat="url in urls">Hello {{url.url}}!</p>
  </body>

</html>

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

How can we utilize a loop to continuously sum up numbers until we reach a multiple of another number, let's say when the total is divisible by 4?

I am trying to create a function in JavaScript that will detect when a given number is not a multiple of 4. If the number is not a multiple of 4, I want to add numbers incrementally until it reaches the closest multiple of 4. Here’s what I have so far: ...

Unable to retrieve JSON data from a PHP file hosted on the server

I have a server-side database with a table called "customers" and a column named "names". My goal is to send a request to the server asking for the first two records in the "customers" table. However, when I execute the program, the browser does not displa ...

Omit node_modules from typescript compilation using gulp-typescript

Having trouble running a gulp task to compile my typescript due to dependency-related errors. /content/node_modules/@angular/core/src/facade/lang.d.ts(12,17): error TS2304: Cannot find name 'Map'. /content/node_modules/@angular/core/src/facade/l ...

Is it possible to create a website with a single session for all users using JavaScript

Greetings everyone, I am excited to be posting for the first time on stackoverflow. After dedicating a week to learning javascript and achieving some things I am proud of, I have hit a roadblock. As a self-learner, I kindly ask for your understanding. Cur ...

JavaScript forEach functionality is not compatible with Dynamics CRM 2016

I'm currently working on writing some JavaScript code for a ribbon button in Dynamics CRM 2016 that will extract phone numbers from a list of Leads displayed in the Active Leads window. However, I've encountered an error message when attempting ...

Generate a dynamic kendo dropdown with data sources assigned in separate methods

Creating a kendo dropdown list dynamically based on the number of received id's is presenting a challenge. A method has been implemented to loop through each id and generate a corresponding dropdown with that id. These dropdowns are not all generated ...

Use Jquery to retrieve the innerhtml content

Hey there! I'm currently in the process of learning Jquery and have encountered an issue with accessing form elements. My script is designed to open a div and then fill it with a predefined HTML form. To achieve this, I'm using ajax to fetch the ...

Traversing a deeply nested array of objects, comparing it with a separate array of objects

I am currently learning Javascript and facing a challenge involving looping through nested arrays of objects and filtering another array based on specific properties. Let's take a look at the structure of both arrays: const displayArr = { section ...

Processing the retrieved object from Dropbox API using Node.js and Express

I've been attempting to carry out a simple task like uploading a file to Dropbox. The file uploads successfully, but I'm in need of the response that contains details such as the file name, size, and path. I understand that I'm getting lost ...

The CloudWatch logs for a JavaScript Lambda function reveal that its handler is failing to load functions that are defined in external

Hello there, AWS Lambda (JavaScript/TypeScript) is here. I have developed a Lambda handler that performs certain functions when invoked. Let me walk you through the details: import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' ...

Navigating the challenges presented by CORS (Cross-Origin Resource Sharing) and CORB (Cross-Origin Read Blocking) when utilizing the FETCH API in Vanilla Javascript

Looking to update text on a website using data from a JSON file on another site? This scenario is unique due to restrictions - can't use JQuery or backend elements like Node/PHP. Wondering if vanilla JavaScript can solve the problem? While some worka ...

"Learn the technique of adding a new data attribute before every element in a step-by-step

I am currently working with the following HTML code: <div id="elem"> <div data-foo="aaa"></div> <div data-foo="aaa"></div> <div data-foo="aaa"></div> <div data-foo="bbb"></div> < ...

Causing a click event to occur results in crashing the browser

Take a look at this link: example on jsfiddle Why does the click event keep triggering multiple times when a div is clicked, eventually causing the browser to crash? What could be causing this issue and how can it be resolved? The actual div contains a l ...

Encasing extracted content in <p> tags

On my Wordpress Site, I have extracted images and text separately to use in different sections of my single.php file. Utilizing HTML within the Bootstrap 3 framework: <div class="row"> <div class="col-md-12"> <?php ...

What is the process for tallying checked checkboxes in a functional component using React Native?

The Whole Code is Right Here Within this code, you will find two flat lists: one displaying category names and the other showing their subcategories with checkboxes. I am looking to implement a feature where if a user checks multiple or just one checkbox ...

What is the best way to adjust the width of a textarea based on its content

How can I dynamically set the width of a React Semantic UI textarea based on its content? Setting min-width doesn't seem to be working. Any suggestions? <Textarea key={idx} defaultValue={formattedText} className="customInpu ...

Having trouble accessing functions in Typescript when importing JavaScript files, although able to access them in HTML

Recently, I started incorporating TypeScript and React into my company's existing JavaScript code base. It has been a bit of a rollercoaster ride, as I'm sure many can relate to. After conquering major obstacles such as setting up webpack correc ...

What is the best way to output information to a webpage using json_encode in PHP?

I've implemented a button on my webpage that triggers a database call using ajax, so the page can dynamically display the data without requiring a refresh. Oddly, when I click the button and inspect the source and network tab, everything seems to be f ...

Executing axios calls within other axios calls and altering state in React before all calls have completed

Currently, I am working on implementing nested axios calls to create the desired object by making multiple API requests. However, I am facing an issue where the state updates before all requests have finished, causing my table to populate entry by entry ...

Obtain Rails database queries in real-time

Is it possible to retrieve database results dynamically in Rails? For instance, if I have a list of cities indexed by ID, can I pass the ID to the view based on the city name, similar to this JavaScript method (even though I know this code won't work) ...