Ganaraj
Ganaraj

Reputation: 26841

Watch not firing in a directive with isolate scope

I was attempting to do something with D3 and Angular. I am not sure that this is something to do with D3 at all but have left it in there just so I could reproduce all that I was trying..

Here is a plunk that reproduces my problem.

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

What I am attempting to do is, create data array and produce a set of d3 svg circles based on that data. The directive created should "watch" this data array and create or delete more circles based on the array shrinking or expanding.. I think the logic is pretty simple to follow from there. To ensure that I do this at a later time, I am doing the addition of a new value into the array using $timeout.

Upvotes: 0

Views: 533

Answers (1)

Anders Ekdahl
Anders Ekdahl

Reputation: 22943

Well, first off, this code: <circles data="obj.dataArray"></circles> seems wrong because you don't define dataArray anywhere on obj in your scope.

So this:

function($scope,model,$timeout) {
    $scope.obj = {};
        model.data[0] = 20;
        model.data[1] = 30;
        model.data[2] = 40;
        model.data[3] = 50;

        $timeout(function(){

            model.data.push(Math.random()*100);
            console.log(model.data);
        },1000);
}

Should probably be some like this:

function($scope,model,$timeout) {
    $scope.model = model;
    $scope.model.data[0] = 20;
    $scope.model.data[1] = 30;
    $scope.model.data[2] = 40;
    $scope.model.data[3] = 50;

    $timeout(function(){
        $scope.model.data.push(Math.random()*100);
        console.log($scope.model.data);
    },1000);
}

And this: <circles data="obj.dataArray"></circles> should be <circles data="model"></circles>.

Now in your directive, you've set up the scope like this:

scope : {
    data : '&'
},

but that should be:

scope : {
    data : '='
},

since you want a reference to the object represented by the data attribute. & are for when attributes contain expressions that you want to execute.

So with those changes, scope.data in your directive now contains a reference to your "commonModel", so there's no longer any need for the directive to ask for "commonModel". Then change your $watch to watch on "data.length" to know when items have been added or removed to it.

Something like this: http://plnkr.co/edit/sa9blROCm8FFhRQSEWii

Upvotes: 1

Related Questions