Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - Angular JS dynamic ng-src not working in 1.2.0-rc.2

I'm trying to implement a video element in an angular JS app and the ng-src won't read the scope variable

I'm using 1.2.0-rc.2

<!DOCTYPE html>
<html ng-app="ngView">

<head>
   <script src="http://code.angularjs.org/1.2.0-rc.2/angular.min.js"></script>

   <script>
   var app = angular.module('ngView', []);
   function MyControl($scope){
      $scope.file = '1234.mp4';
   }
  </script>
  </head>
  <body ng-controller="MyControl">
      <video controls  ng-src="http://www.thebigdot.com/{{file}}"></video>
  </body>
</html>

If I use a much older version AngularJS lib, it works.

cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.3/angular.min.js (works)

Is this a bug in the latest release or has it been disabled on purpose? What is the work around ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Angular 1.2 ships with Strict Contextual Escaping (SCE) enabled by default. You need to tweak your code slightly to make it work.

HTML

Change the markup so that the ng-src binds to a variable and not a URL + variable as you had it setup before:

<video controls ng-src="{{videoUrl}}"></video>

JavaScript

Add $sce to inject the SCE provider and use the $sce.trustAsResourceUrl method to set videoUrl.

function MyControl($scope, $sce) {
    var videoUrl = 'http://www.thebigdot.com/1234.mp4';
    $scope.videoUrl = $sce.trustAsResourceUrl(videoUrl);
}

Here's a JS Bin demo of this setup in action.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...