shaik
shaik

Reputation: 35

update view whenever data inside service changes

angular.module("taskAssign")
    .service('shareData', function(){
    this.assignees = "dummy";
});
.directive("textArea", textAreaDir)

function textAreaDir(shareData){
    return{
        restrict:'EA',
        template:'<textarea></textarea>',
        replace: true,
        scope : {

        },
        link:function(scope, iElm, iAttrs, controller,ngModel){
             scope.$watch(shareData.assignees,function (old,newv) {
                 console.log(old);
                 console.log(newv);
             });

        },
        controller:function($scope){
        $scope.$watch('shareData.assignees', function (newVal, oldVal, scope) {
            if(newVal) { 
              console.log(newVal);
            }
          });
        }
    }
}

I wanted to update the view in textArea directive with ltest values of sharedata service,it is only showing the initial value of shareData service later if shareData updates view is not updating

Upvotes: 1

Views: 55

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

You need to put watch as a function on service variable shareData.assignees, basically that function will evaluate on each digest cycle.

And inside your controller you need to inject shareData service dependency to use it.

Code

scope.$watch(function() {
    return shareData.assignees; //this will evaluate on each digest, and run callback when value gets changed.
}, function(old, newv) {
    console.log(old);
    console.log(newv);
});

Upvotes: 1

saikumar
saikumar

Reputation: 1051

create shareData variable in your scope, then watch will trigger

controller:function($scope){
        $scope.shareData = shareData
        $scope.$watch('shareData.assignees', function (newVal, oldVal, scope) {
            if(newVal) { 
              console.log(newVal);
            }
          });
        }
 

Upvotes: 0

Related Questions