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

Angularjs 如何在angular js中添加观察者?,angularjs,angularjs-directive,angularjs-scope,jasmine,karma-jasmine,Angularjs,Angularjs Directive,Angularjs Scope,Jasmine,Karma Jasmine,我正在尝试在我的演示中添加watcher。我可以像这样在对象中添加watch $scope.$watch('username',function(newvalue,oldvalue){ console.log(newvalue +":"+oldvalue); $scope.newmessage=newvalue.toUpperCase(); }) 它工作得很好。但是当我尝试测试它时,它会给我错误,这是我的代码 describe('value check'

我正在尝试在我的演示中添加watcher。我可以像这样在对象中添加watch

$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')
  });
});
普朗克


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

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

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

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

请参阅plunker:

用户名在任何地方都没有定义,遗漏了一些内容?@chantu为什么它不起作用我只是删除了创建控制器功能你有什么想法吗?