2013-05-09 201 views
0

我有以下代碼。出於某種原因,測試1失敗。誰能告訴我爲什麼?

angular. 
    module('myModule', []). 
    directive('myDirective', function() { 
     return { 
      restrict: 'E', 
      scope: { 
       myAttr: '=' 
      }, 
      link: function (scope, element, attrs) { 
       element.text(scope.myAttr); 
      } 
     } 
    }); 

describe('test', function() { 
    var compile, rootScope; 

    beforeEach(module('myModule')); 

    beforeEach(inject(function ($compile, $rootScope) { 
     compile = $compile; 
     rootScope = $rootScope; 
    })); 

    describe('test 1', function() { 
     it('test', function() { 
      scope = rootScope.$new(); 

      // scope.myVar = "test"; 

      element = compile('<my-directive my-attr="myVar" />')(scope); 
      scope.$digest(); 

      scope.myVar = "test"; 
      scope.$digest(); 

      expect(element.text()).toBe("test"); 
     }); 
    }); 

    describe('test 2', function() { 
     it('test', function() { 
      scope = rootScope.$new(); 

      scope.myVar = "test"; 

      element = compile('<my-directive my-attr="myVar" />')(scope); 
      scope.$digest(); 

      scope.myVar = "test"; 
      scope.$digest(); 

      expect(element.text()).toBe("test"); 
     }); 
    }); 
}); 

回答

0

element.text(scope.myAttr);需要被包裹在一塊手錶,像這樣:

angular. 
    module('myModule', []). 
    directive('myDirective', function() { 
     return { 
      restrict: 'E', 
      scope: { 
       myAttr: '=' 
      }, 
      link: function (scope, element, attrs) { 
       scope.$watch('myAttr', function() { 
        element.text(scope.myAttr); 
       }); 
      } 
     } 
    }); 
相關問題