如何在 angular js 中添加观察者?

how to add watcher in angular js?

我正在尝试在我的 demo.I 中添加观察者 我能够像那样在对象中添加观察者

$scope.$watch('username',function(newvalue,oldvalue){
        console.log(newvalue +":"+oldvalue);
        $scope.newmessage=newvalue.toUpperCase();
    })

它工作正常。但是当我尝试测试时它给我错误这里是我的代码

describe('value check', function() {
  var $scope,
    ctrl,
    fac,
    $httpBackend;
  beforeEach(function() {
    module('app');

  });
  afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  beforeEach(inject(function($rootScope, $controller, _$httpBackend_) {
    $scope = $rootScope.$new();
    $httpBackend = _$httpBackend_;

    createController = function() {
      return $controller('cntrl', {
        '$scope': $scope
      });
    };

  }));

  describe('watch check', function() {
    beforeEach(function() {
      $scope.$digest();
    });

    it('should init', function(){
      expect($scope.newmessage).toBeUndefined();
    });

    it('should upper case',function() {
      var controller = createController();
      $scope.message='naveen';
      $scope.$digest();
      expect($scope.newmessage).toEqual('NAVEEN');
    });
  });


  it("tracks that the spy was called", function() {
    var response = [{
      "name": "naveen"
    }, {
      "name": "parveen"
    }]
    $httpBackend.whenGET('data.json').respond(response);
    var controller = createController();

    $httpBackend.expectGET('data.json').respond(response);

    $scope.getData();
    $httpBackend.flush();

    expect($scope.data[0].name).toEqual('naveen')
  });
});

笨蛋

http://plnkr.co/edit/NhazRDVM01DCDQWw8yzV?p=preview

第一个错误是意外请求,可以通过在 should uppercase 测试用例中模拟 data.json 请求来解决。

第二个错误可以通过 $scope.username = 'naveen' 而不是 $scope.message = 'naveen' 来修复,因为您实际上是在观察用户名更改,而不是消息更改。

第三个错误是当你初始化手表时,它被未定义的新值触发。要解决此问题,请检查它是否在控制器中未定义:

if (newvalue) {
       $scope.newmessage = newvalue.toUpperCase();
}

查看插件:http://plnkr.co/edit/OBUcoNGPdfRwy3hwR4KZ?p=preview