AngularJS动态模型

时间:2015-04-26 20:04:54

标签: javascript angularjs angularjs-directive

指令

(function() {

    'use strict';

    angular
        .module('app.colorslider.directive', [])
        .directive('colorSlider', [
            '$timeout',
            '$rootScope',
            'ColorSliderService',
            function($timeout, $rootScope, ColorSliderService) {
                return {
                    restrict: 'EA',
                    scope: {
                        array: '=',
                        shape: '=',
                        shapeindex: '=',
                        type: '='
                    },
                    templateUrl: 'views/directive/colorslider.html',
                    link: function(scope, elem, attrs) {

                        console.log(scope.type);

                        scope.fill = {
                            blue: 128,
                            green: 128,
                            red: 128,
                            opacity: 1
                        }

                        scope.stroke = {
                            blue: 128,
                            green: 128,
                            red: 128,
                            opacity: 1,
                            width: 1
                        }
                        scope.colorSlider = function() {
                            scope[scope.type].combined = ColorSliderService.rgbToHex(parseInt(scope[scope.type].red), parseInt(scope[scope.type].green), parseInt(scope[scope.type].blue));
                            console.log(scope[scope.type].combined);
                        };
                    }

                };
            }
        ]);
}());

HTML

<color-slider type="'stroke'" shape="selectedshape" array="linesArray" shapeindex="selectedshapeindex"></color-slider>

<color-slider type="'fill'" shape="selectedshape" array="linesArray" shapeindex="selectedshapeindex"></color-slider>

colorslider.html

<input class="colorInt" type="text" size="3" id="redInt" maxlength="3" value="{{[type].red}}" style="display: none">

我制作了上述指令,以便它可以选择strokefill颜色的颜色。 directive属性允许将type传递给指令范围。

该指令加载但我注意到 colorslider.html 根本没有显示该值,我在这里错过了什么?

这是在指令模板中显示值的错误方法吗? value="{{[type].red}}"

1 个答案:

答案 0 :(得分:2)

指令模板如下所示:

<input class="colorInt" type="text" value="{{this[this.type].red}}" size="3" id="redInt" maxlength="3">

模板this内部指向当前范围对象。因此,模板中的this.type对应于链接功能中的scope.type。同样,链接功能中的scope[scope.type].combined会转换为模板中的this[this.type].combined