0

I'm new to Angular.js which is why this question might be a very basic one but I would like to know how I can display elements via $scope. Very simple:

<div id="view" ng-controller="images">{{ image }}</div>

and

function images($scope) {
  $scope.image = '<img src="img/file.png">';
}

in this example it will only display the image tag as a string. Obviously one could to

<div id="view" ng-controller="images"><img src="{{ image }}"></div>

and use the source as variable

$scope.image = 'img/file.png';

but thats not what I am searching for. Is it possible to display elements as DOM element, not as a string.

4
  • 1
    Actually, you "can't" do <img src="{{ image }}"> because the dom will be loaded before the {{ image }} will be evaluated (or something like that. You have to use ng-src. I know thats not your question but i just wanted to let you know before you go on Commented Aug 6, 2014 at 16:24
  • Now, to answer you question, what you want to look up is a directive. Thats at least what I would do based on what you are asking. Commented Aug 6, 2014 at 16:25
  • I tried <img src="{{ image }}"> and it works fine though. Commented Aug 6, 2014 at 16:25
  • 1
    yes it works, but its buggy and won't work every time. See here --> docs.angularjs.org/api/ng/directive/ngSrc Commented Aug 6, 2014 at 16:26

2 Answers 2

1

You can use a directive (basically a template of sorts) to do what you want.

So you have your app with your controller and your directive:

angular.module('myApp', [])
    .controller('ImagesController', function($scope) {
        $scope.image = '/url/to/my/img.png';
    })
    .directive('showImage', function() {
        return {
            restrict: 'AE',
            replace: 'true',
            templates: '<img ng-src="{{ image }}">'
        };
    })

and then in your html you would have something like so:

<html ng-app="myApp">
    <body>
        <div id="view" ng-controller="ImagesController">
            <show-image></show-image>
        </div>
    </body>
</html>

<show-image would then be replaced with the template within the directive, <img ng-src="{{ image }}">

Sign up to request clarification or add additional context in comments.

Comments

1

according to the doc https://docs.angularjs.org/api/ng/directive/ngBindHtml

you have to bind it as html

 <div ng-bind-html="imagesafe"></div> 

in your controller you have to sanitize the variable

App.controller('Ctrl', ['$scope', '$sce', function($scope, $sce) {
    $scope.image = '<img src="img/file.png">';
    $scope.imagesafe =  $sce.trustAsHtml($scope.image);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.