【问题标题】:Where should parts of a custom AngularJS directive be kept?自定义 AngularJS 指令的一部分应该保存在哪里?
【发布时间】:2013-03-15 11:16:51
【问题描述】:

我正在尝试创建一个自定义 Angular 指令,该指令使用 KineticJS 根据范围内的值在画布上进行绘制。我打算创建一个服务,然后根据接收 JSON 响应的 $http 调用更新范围。那时我希望指令循环遍历范围内的值并为每个值创建一个动力学节点。

但是,我不确定我应该在控制器内部还是在指令的链接函数中执行此操作。如果我要在链接函数中进行更新,我会使用 scope.$watch 还是其他东西?

我已经创建了这样的自定义指令:

angular.module('history.directives', [])
    .directive('kinetic', function() {
        var kineticContainer = '<div id="container"></div>';
        return {
            restrict: 'E',
            compile:function (tElement, tAttrs, transclude) {
                tElement.html(kineticContainer);
            },
            controller: KineticCtrl
        };
});

控制器看起来像这样:

function KineticCtrl($scope) {
    $scope.stage = new Kinetic.Stage({
        container: 'container',
        width: window.innerWidth,
        height: window.innerHeight - $('.navbar').outerHeight()
    });

    $scope.drawNode = function(posx, posy) {
        var layer = new Kinetic.Layer();
        var group = new Kinetic.Group({
            x: posx,
            y: posy
        });

        var line = new Kinetic.Line({
            points: [0, 25, 500, 25],
            stroke: 'black',
            strokeWidth: 4
        });

        var text = new Kinetic.Text({
            text: 'www.google.com',
            fontSize: 18,
            fontFamily: 'FontAwesome',
            fill: '#555',
            width: 300
        });

        group.add(line);
        group.add(text);
        layer.add(group);
        $scope.stage.add(layer);
    };

    $scope.drawNode(200, 400);
    $scope.drawNode(800, 400);
    $scope.drawNode(400, 100);
}

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript angularjs kineticjs


    【解决方案1】:

    Difference between the 'controller', 'link' and 'compile' functions when defining a directive

    总而言之,指令的控制器和链接功能之间几乎没有区别。如果这很重要,控制器将首先运行,但我认为它不会在这里运行 - 因为您通过 $http 检索数据,您必须在控制器或链接函数中使用 $watch 才能触发您的逻辑数据可用。

    【讨论】:

    • 好的,当你说在控制器或链接函数中使用 $watch 时......有什么理由让我应该做一个而不是另一个?
    • @sailboatlie,对于您显示的代码,应该没问题。 (需要一个控制器,例如,如果您想在其上定义一些其他指令可以调用的方法,但您在这里没有这个要求。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 2019-12-03
    • 2016-11-09
    • 2011-07-12
    相关资源
    最近更新 更多