AngularJS:这是在 model/content 中编写处理更新的指令的正确方法吗?
AngularJS: Is this the right way to write a directive handling updates in the model/content?
我必须创建一个 html 页面,其中包含将从 json 文件加载的 svg 元素。 json 文件是使用 $http 和 returns 承诺加载的。
在 html 文件中,我有以下标记:
<ext-svg content="svg"></ext-svg>
svg
将首先包含未定义,当 json 加载有效的 svg 内容时。
我的指令定义为:
angular.module('myApp.directives')
.directive('extSvg', function () {
"use strict";
return {
restrict: 'E',
scope: {
content: '='
},
link: function (scope, element) {
scope.$watch('content', function (value) {
if (value) {
element.replaceWith('<svg>' + scope.content + '</svg>');
}
});
}
};
});
呈现的页面包含例如:
<svg><circle cx="10" cy="10" r="10" fill="yellow" stroke="black" stroke-width="1"></circle></svg>
它起作用了,但这是实现它的正确方法吗?
也许是使用 ngSanitize 模块并直接绑定来自控制器的值的不同方法,这样您实际上不需要指令就可以在需要插入 SVG 的任何地方使用 ng-bind-html无需替换元素 Look at this fiddle
所以在你的 HTML
<div ng-bind-html="svg"></div>
并在您的控制器中
$scope.svg = $sce.trustAsHtml('<svg><circle r="50"/></svg>'); //$sce needs to be injected in your controller
我必须创建一个 html 页面,其中包含将从 json 文件加载的 svg 元素。 json 文件是使用 $http 和 returns 承诺加载的。
在 html 文件中,我有以下标记:
<ext-svg content="svg"></ext-svg>
svg
将首先包含未定义,当 json 加载有效的 svg 内容时。
我的指令定义为:
angular.module('myApp.directives')
.directive('extSvg', function () {
"use strict";
return {
restrict: 'E',
scope: {
content: '='
},
link: function (scope, element) {
scope.$watch('content', function (value) {
if (value) {
element.replaceWith('<svg>' + scope.content + '</svg>');
}
});
}
};
});
呈现的页面包含例如:
<svg><circle cx="10" cy="10" r="10" fill="yellow" stroke="black" stroke-width="1"></circle></svg>
它起作用了,但这是实现它的正确方法吗?
也许是使用 ngSanitize 模块并直接绑定来自控制器的值的不同方法,这样您实际上不需要指令就可以在需要插入 SVG 的任何地方使用 ng-bind-html无需替换元素 Look at this fiddle
所以在你的 HTML
<div ng-bind-html="svg"></div>
并在您的控制器中
$scope.svg = $sce.trustAsHtml('<svg><circle r="50"/></svg>'); //$sce needs to be injected in your controller