使用动态数组填充angularjs范围

时间:2018-02-23 14:30:02

标签: javascript angularjs ecmascript-5

My Angular App适用于

  <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>

但它不能与

一起使用
  <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>

更新:仍然无法运作

 <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>
  

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

1 个答案:

答案 0 :(得分:1)

用{替换$scope.push(new myUrl($sce.trustAsResourceUrl(url))); $scope.push(new myUrl($sce.trustAsResourceUrl(url.url)));

https://plnkr.co/edit/tpl:FrTqqTNoY8BEfHs9bB0f?p=preview

 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="angular.js@1.2.x" 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>