Angular手表问题



这是我第一次使用Angular的watch函数,显然我没有让它工作。我有一个服务叫做apiService,它有一个变量myFile。我正在将服务注入我的控制器,并希望观察apiService.myFile值的变化。不幸的是,手表只在打开网页时被调用,而不是当apiService.myFile变量实际改变时。下面是手表的代码:

$scope.$watch(function(){return apiService.myFile}, function (newVal, oldVal, scope) {
    console.log("service changed: "+newVal +" : "+oldVal+" : "+ scope);
});

为什么myFile变化时不调用它?

更新1:这就是我如何在服务

中更新apiService.myFile的值
ApiService.prototype.uploadFile = function(fileContent) {
    $.ajax({
        url: "/space_uploadFile/",
        type: "POST",
        dataType: "json",
        data: {
            fileContent: fileContent
        },
        contentType: "application/json",
        cache: false,
        timeout: 5000,
        complete: function() {
          //called when complete
          console.log('process complete');
        },
        success: function(data) {
            this.myFile =data;
            console.log("this.myFile: "+this.myFile);
            console.log('process success');
       },
        error: function() {
          console.log('process error');
        },
      });
};

我在一个plunkr中添加了这个(因为你没有),这对我来说是有效的:

旁注:下次创建一个例子来演示你的问题(plunkr),这样我们就可以消除你的问题(例如打字错误)。

var app = angular.module('app', []);
app.controller('mainController', function($scope, apiService) {
  $scope.changeValue = function() {
    apiService.myFile += "!";
  };
  $scope.$watch(function(){return apiService.myFile}, function (newVal, oldVal, scope) {
    console.log("service changed: "+newVal +" : "+oldVal+" : "+ scope);
    $scope.someValue = newVal;
  });
});
app.service('apiService', function() {
  this.myFile = "Test";
});
和相应的HTML:
<body ng-controller="mainController">
  <h1>Hello Plunker!</h1>
  {{someValue}}
  <button ng-click="changeValue()">Click</button>
</body>

https://plnkr.co/edit/DpDCulalK1pZ8J0ykh2Z?p =

预览

顺便说一句:$watch部分是你问题的副本,它对我来说很有效。

编辑:显然OP使用了$。这个值是在succeshandler (Angular上下文之外)内部更新的。所以这里没有触发消化循环。要解决这个问题,你应该使用angular提供的$http服务(或者不使用它)。
var self = this;
self.$http.post("/space_uploadFile/",
{ fileContent: fileContent },
{ 
    cache: false,
    timeout: 5000
})
.then(function (data) {
    self.myFile = data;
    console.log("self.myFile: " + self.myFile);
    console.log('process success');
},
function () {
    console.log('process error');
});

Edit2:显然OP也在成功处理程序中使用this来访问控制器上的变量。这行不通,所以我使用上面示例中的self模式来解决这个问题。

我习惯了这种语法:

scope.$watch('name', function(newValue, oldValue) {
  scope.counter = scope.counter + 1;
});

其中name是属性的名称——在本例中为myFile

最新更新