AngularJS调用另一个指令函数

时间:2015-08-18 09:51:19

标签: angularjs

我在页面上有一个指令,它将颜色应用于它的元素。 它可能看起来像这样:

.directive('colours', function () {
    return {
        restrict: 'A',
        scope: {
            colours: '='
        },
        template: '<div class="col-md-4" id="panel-1"><p>This is panel 1</p></div><div class="col-md-4" id="panel-2"><p>This is panel 2</p></div><div class="col-md-4" id="panel-3"><p>This is panel 3</p></div>',
        link: function (scope, element) {

            // Get our panel children
            var children = element.children();

            // This is just an example, so excuse the code
            for(var i = 0; i < children.length; i++) {
                var child = angular.element(children[i]);

                child.css('background-color', scope.colours[i]);
            }
        }
    };
})

这只是一个例子,但真正的指令有数据库颜色,svgs等,所以我无法在codepen中复制它。 我想要做的是在同一个视图上创建一个新指令(但不是 colors 指令的子节点)。它可能看起来像这样:

.directive('colourSwapper', function () {
    return {
        restrict: 'A',
        scope: {
            colours: '=colourSwapper'
        },
        template: '<button class="btn btn-default" type="button" ng-click="swap(true)"><span class="fa fa-chevron-left"></span></button> Swap colours <button class="btn btn-default" type="button" ng-click="swap()">    <span class="fa fa-chevron-right"></span></button>',
        link: function (scope, element) {

            // Get our colours
            var colours = scope.colours;

            // Create our function
            scope.swap = function (opposite) {

                // If we want to go in the opposite direction
                if (opposite) {

                    // Shift the array in reverse
                    colours.unshift(colours.pop());

                // Else
                } else {

                    // Shift the array
                    colours.push(colours.shift());
                }
            };
        }
    };
});

我已将相同的颜色数组传递给此指令。我现在想做的是改变颜色的顺序,然后将它们重新应用到元素。 我希望能够调用一个函数而不是添加一个手表(原因就是我的颜色指令是一个父母的孩子,需要一些指令而且我不希望手表中有太多的手表我假设手表太多是坏事。

有谁知道我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用ng-style绑定范围变量中的颜色。然后更改范围变量将更新颜色。在添加ng-style属性后进行编译也很重要。

http://plnkr.co/edit/MmcnkWLhaVKZmLonhzlx?p=preview

    for (var i = 0; i < children.length; i++) {
      var child = angular.element(children[i]);

      child.attr('ng-style', '{\'background-color\': colours[' + i + ']}');
      $compile(child)(scope);
    }
相关问题