1

我查看了各种类似的问题,例如this onethis onethis onethis onethis one,这些问题在我自己找到解决方案之前未能为我的问题提供解决方案。但是,它仍然不像是“正确”的 Angular 方式,所以我向社区征求意见。

这是设置。我有一个布局模板(index.html):

<!DOCTYPE html>
<html ng-app="app">    
<head>
    ...
</head>
<body role="document">
    <div id="wrapper" class="container" role="main" ng-controller="mainController">

        <div id="header">
            ...
        </div>

        <div id="diagram" ng-view="ng-view"></div>

        <div id="footer>
            ...
        </div>

        <script>
            ...
        </script>

    </div>
</body>
</html>

我有一个局部视图模板(diagram.html)。注意自定义指令,解释如下:

<div my-diagram ng-bind-html="diagram"></div>

这是我的路由配置,指定局部视图模板和控制器:

angular.module("app", ["ngRoute", "ngSanitize", "controllers", "directives"])
    .config(["$routeProvider",
        function ($routeProvider) {
            $routeProvider
                .when("/process/:processId", {
                    templateUrl: "diagram.html",
                    controller: "processDiagramController"
                });

        }]);

这是用于局部视图的控制器。它使用 $routeParams 中的 processId 值通过 $http.get() 进行调用,以检索它分配给绑定到模板的 $scope.diagram 的 SVG 数据:

angular.module("controllers")
    .controller("processDiagramController", ["$scope", "$http", "$routeParams", "$sce",
        function ($scope, $http, $routeParams, $sce) {

            var onError = function (response) {
                $scope.errors.push(response.data);
            }

            var onDiagram = function (response) {
                $scope.diagram = $sce.trustAsHtml(response.data);
            }

            $scope.errors = [];

            $http.get("/" + $routeParams.processId + ".svg").then(onDiagram, onError);

        }
    ]);

我的问题是弄清楚如何在将 SVG 内容添加到 DOM 后对其运行代码。当然,在 Angular 中进行任何 DOM 操作的正确位置是在指令中,所以我写了一个:

angular.module("directives", [])
    .directive("myDiagram", function () {
        return {
            link: function(scope, element, attrs) {
                scope.$watch(function() {
                    return element.html();
                },
                function () {
                    diagram.process(element);
                });
            }
        };
    });

在将 SVG 内容添加到 DOM 之后,我可以让 diagram.process() 函数运行的唯一方法是在 element.html() 上使用 $watch,如图所示。这对我来说是“错误的”,我想知道是否有更“正确”的方式。

4

0 回答 0