Search code examples
angularjsangular-directive

directive Isolated Scope undefined, angularjs 1.3


I'm doing a directive I have a strange behavior when I do a console over the scope I get a value passed from the controller scope printed, but when I try to access it from the scope is undefined like scope.model

this is the code:

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>

Please take a look to the console output: console output


Solution

  • I ended up by adding a $watch over value of the scope and using the new value assigned.

    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);
    
            }
        };