角度表问题

时间:2016-09-20 06:11:30

标签: javascript angularjs

这是我第一次使用Angular的手表功能,显然我不能让它工作。 我有一个名为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');
        },
      });

};

2 个答案:

答案 0 :(得分:2)

我在一个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=preview

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

编辑:显然OP正在使用$ .ajax进行ajax调用,并且值在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也在succeshandler中使用this来访问控制器上的变量。这不会起作用,所以我使用上面示例中的自我模式来解决它。

答案 1 :(得分:-3)

我习惯了这种语法:

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

其中name是您的媒体资源的名称 - 在本例中为myFile