-1

I have some constants defined in my app like so:

angular.module('MyModule')

.constant('myConstant', {
    'userId': '0000',
    'playerId': '1111'
});

I'd like to use them in a script URL like so:

<script ng-src="http://domain.com/{{myConstant.userId}}/{{myConstant.playerId}}"></script>

I'm aware that $sce disallows this type of interpolation, so I've tried using a scope function to return sanitized tokens (using Controller As syntax):

{{ctrlAlias.getUserId()}}

ctrlAlias.getUserId = function ($sce) {
    return $sce.trustAsResourceUrl(ctrlAlias.ctrlVar.userId);
};

This is apparently wrong, though. It returns the same error:

Strict Contextual Escaping disallows interpolations that concatenate multiple expressions when a trusted value is required.

Is this sort of tokenization feasible in a script source, and what's the right way to handle it? Should I be employing a service to build the entire source URL instead? I'd rather not use Grunt's string replacement in this case.

Thanks a bunch.

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • you can to load your script with a dinamic load function, like this examples: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml You could to use with a $timeout() to decouple load from angular digest – Joao Polo Jan 29 '16 at 22:19
  • Thanks, but I'm looking for an Angular solution. – isherwood Jan 29 '16 at 22:20
  • 1
    I don't think you should have an issue if you pass the full URL to $sce. I have some code that does this for an iframe without issue. I don't think it's real clear what you are passing to `trustAsResourceUrl` – Matthew Green Jan 29 '16 at 22:21
  • https://github.com/urish/angular-load is an angular solution. – Joao Polo Jan 29 '16 at 22:22
  • This isn't a dynamic load question. It's about using constants in various places, including script URLs. – isherwood Jan 29 '16 at 22:23
  • Here is an example that covers pretty much what I ended up doing: http://stackoverflow.com/a/24163343/1078110 – Matthew Green Jan 29 '16 at 22:25
  • @MatthewGreen True, but that's not what I'm after here. Consider it an exploration of another tool in the belt. – isherwood Jan 29 '16 at 22:25
  • Yes, I know... I'm trying to see other alternatives to $sce problem. – Joao Polo Jan 29 '16 at 22:26

1 Answers1

0

It looks like you are passing the userId to the $sce.trustAsResourceUrl function.

The way trustAsResourceUrl works is that it creates an alias to a url that you may later reference in the ng-src attribute.

This will probably work:

$scope.url = $sce.trustAsResourceUrl('http://domain.com/' + myConstant.userId + '/' + myConstant.playerId

<script ng-src="{{url}}"></script>
sstendal
  • 3,148
  • 17
  • 22