phan ngoc
phan ngoc

Reputation: 191

How to allow ng-model input html in angularjs

I have html code:

<div class="inner-content-linkaudio">
  <label for="linkaudio">Link audio</label>
  <input type="url" name="linkaudio" ng-model="linkaudio" class="form-control">
</div>

But when I enter to input, and press button submit form, I have error:

Error: [$interpolate:interr] Can't interpolate: {{postcurrent.linkaudio}}
Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate policy.  URL: 

How do I can allow enter url and submit form without error? Thank you.

Upvotes: 2

Views: 814

Answers (2)

Igor Raush
Igor Raush

Reputation: 15240

This is a result of Strict Contextual Escaping (SCE). Angular will refuse to load/render a string value which has not been explicitly trusted as a resource URL by the SCE policy. This is done as a security measure, in order to maintain control what resources can be loaded into your app.

You can write a directive which extends a sibling NgModelController to trust all input as a resource URL

angular.module('test', [])
  .directive('trustedUrl', ['$sce', function($sce) {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        ngModel.$parsers.push(function(value) {
          return $sce.trustAsResourceUrl(value);
        });
      }
    }
  }]);

which can then be used as

<input type="url" ng-model="url" trusted-url />
<audio ng-src="{{ url }}" controls></audio>

Here is a working Plunker. You can test by pasting an audio URL into the input.


Another option is to use $sceDelegateProvider.resourceUrlWhitelist([...]) to whitelist only some URLs as those which can be loaded into your app.

Upvotes: 3

Kole Myers
Kole Myers

Reputation: 61

Make sure your postcurrent variable is defined on the scope

$scope.postcurrent={linkaudio:""};

Upvotes: 0

Related Questions