每当服务内的数据发生变化时更新视

时间:2016-01-13 10:11:45

标签: javascript angularjs angularjs-directive

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

我想用texttest服务的ltest值更新textArea指令中的视图,如果shareData updates视图没有更新,它只显示shareData服务的初始值

2 个答案:

答案 0 :(得分:1)

您需要将watch作为函数放在服务变量shareData.assignees上,基本上该函数将在每个摘要周期进行评估。

在控制器内部,您需要注入shareData服务依赖项才能使用它。

<强>代码

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

答案 1 :(得分:0)

在您的范围内创建shareData变量,然后watch会触发

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