简体   繁体   English

通过angular.js中的作用域变量显示或追加元素

[英]display or append element via scope variable in angular.js

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 . 我是Angular.js的新手 ,这就是为什么这个问题可能是一个非常基本的问题,但是我想知道如何通过$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. 是否可以将元素显示为DOM元素,而不是字符串。

according to the doc https://docs.angularjs.org/api/ng/directive/ngBindHtml 根据文档https://docs.angularjs.org/api/ng/directive/ngBindHtml

you have to bind it as html 您必须将其绑定为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);
}

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中,您将像这样:

<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 }}"> 然后,将<show-image替换为指令<img ng-src="{{ image }}">的模板

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM