paynestrike
paynestrike

Reputation: 4658

angular $watch parent scope variable always fired

html

<div data-select >
     <div data-set-tip tipit='selecting(tips)' ></div>
     <div data-show-tip headsup='selectingtips' ></div>
</div>

js

directive.select= function(){
    return:{
        restrict:'A',
        controller:function($scope){
            $scope.selectingtips = '';
            $scope.selecting = function(tips){
                $scope.selectingtips = tips
            }
        }
    }
}

directive.setTip = function(){
    return {
        restrict:'A',
        scope:{
            tipit:'&'
        },
        link:function(scope,element,attrs){
            element.on('mousestop',function(){
                scope.tipit({tips:'some tips'})
            })
        }
    }

}

directive.showTip = function(){
    return {
        restrict:'A',
        scope:{
            headsup:'&'
        },
        link:function(scope,element,attrs){
            scope.$watch('headsup',function(){
                alert('changed')
            })
        }

    }
}

I want when mouse stop at setTip directive the parent directive variable selectingtips will be set to something, and the showTip directive always listen to the change of selectingtips,and when change happens alert change.

problem

when I refresh the page it will alert change immediately, and when I stop the mouse on setTip directive, nothing happens. note: the selectingtips did get changed when mouse stop at setTip directive.

what my doing wrong?

here is the plunker link

Upvotes: 0

Views: 3412

Answers (1)

Tyler Wanlass
Tyler Wanlass

Reputation: 41

To prevent the $watch from firing on page load you'll need to compare the old and new values of model you're watching:

scope.$watch('headsup',function(newVal, oldVal){
    if(newVal != oldVal)
        alert('changed')
})

See the updated plunker: http://plnkr.co/edit/5kJSZtVA9a8o4tRdnPaT?p=preview

Upvotes: 3

Related Questions