【问题标题】:directive Isolated Scope undefined, angularjs 1.3指令隔离范围未定义,angularjs 1.3
【发布时间】:2014-10-21 17:29:19
【问题描述】:

我正在执行一个指令,当我在 范围 上执行控制台时,我有一个奇怪的行为,我得到一个从打印的控制器范围传递的值,但是当我尝试从范围访问它时未定义,如 scope.model

这是代码:

function() {
        var color = d3.interpolateRgb('#f77', '#77f');  
        return {
            template: '<div></div>',
            restrict: 'E',
            scope:{
                model:'='
            },
            link: function postLink(scope, element, attrs) {

                console.log(scope); //print model
                console.log('scope.model ',scope.model); // undefined

                var width = attrs.width || 940,
                    height = attrs.height || 500,
                    margin = 20;

                var modeler = d3.select(element[0])
                    .append('svg')
                    .attr('width', width)
                    .attr('height', height);

            }
        };
    }

HTML

<d3-directive model="model" width="920" height="510" ></d3-directive>

请查看控制台输出:

【问题讨论】:

    标签: angularjs angular-directive


    【解决方案1】:

    我最终添加了一个 $watch over 范围的值并使用分配的新值。

    return {
            template: '<div></div>',
            restrict: 'E',
            scope:{
                model:'='
            },
            link: function postLink(scope, element, attrs) {
    
                console.log(scope); 
                console.log('scope.model ',scope.model);
    
                scope.$watch('model',function(newValue,oldValue){
                    if(!!newValue){
                        console.log(newValue);
                    }
                });
    
                var width = attrs.width || 940,
                    height = attrs.height || 500,
                    margin = 20;
    
                var modeler = d3.select(element[0])
                    .append('svg')
                    .attr('width', width)
                    .attr('height', height);
    
            }
        };
    

    【讨论】:

    • 有完全相同的问题。似乎使用 $watch 是唯一的选择
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    相关资源
    最近更新 更多