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

display or append element via scope variable in angular.js

本文关键字:显示 变量 追加 元素 作用域 angular js      更新时间:2023-09-26

我是Angular.js的新手,这就是为什么这个问题可能是一个非常基本的问题,但我想知道如何通过$scope显示元素。非常简单:

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

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

将只以字符串的形式显示图像标记。显然可以

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

并使用源作为变量

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

但那不是我要找的。是否可以将元素显示为DOM元素,而不是字符串

你可以使用一个指令(基本上是一个模板)来做你想做的。

你有你的app,你的控制器和你的指令:

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 }}">'
        };
    })

然后在你的HTML中你应该这样写:

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

<show-image替换为指令中的模板,<img ng-src="{{ image }}">

根据doc https://docs.angularjs.org/api/ng/directive/ngBindHtml

必须绑定为HTML

 <div ng-bind-html="imagesafe"></div> 
在你的控制器中

你必须清理变量

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