指令链接中的绑定不起作用

Binding in directive linking not working

本文关键字:绑定 不起作用 链接 指令      更新时间:2024-01-27

我正在尝试制作一个简单的指令,它只返回大写文本。文本是通过绑定从控制器传递的。

基本思想是:

<div ng-controller="MainCtrl as main">
    <div uppercase>{{main.message}}</div>
</div>

我的主要JS文件如下:

angular.module('app', [])
.controller('MainCtrl', function(){
    this.message = 'hello world'
})
.directive('uppercase', function() {
    return {
        restrict: 'A',
        transclude: true,
        template: '<span ng-transclude></span>',
        link: function(scope, el, attr) {
            el.text() = el.text().toUpperCase();
        }
    }
})

我的茉莉花测试如下:

describe("App", function() {
    var $compile
    ,   $rootScope
    ,   $controller
    ,   MainCtrl
    ,   element;
  beforeEach(module('app'))
  beforeEach(inject(function(_$compile_, _$rootScope_, _$controller_){
    $compile = _$compile_;
    $rootScope = _$rootScope_;
    $controller = _$controller_;
    MainCtrl = $controller('MainCtrl');

  }))
  describe("MainCtrl", function() {
    it("should have a message property", function() {
      expect(MainCtrl.message).toBe('hello world');
    });
  });
  describe("Uppercase directive", function() {
    it("should return uppercase text", function() {      
      element = '<p superman>{{MainCtrl.message}}</p>';
      element = $compile(element)($rootScope);
      $rootScope.$digest();
      expect(element.text()).toBe('HELLO WORLD');
    });
  });

});

使用$timeout等待Angular绑定完成,这就是使用.text():的方式

.directive('uppercase', function($timeout) {
    return {
        restrict: 'A',
        transclude: true,
        template: '<span ng-transclude></span>',
        link: function(scope, el, attr) {
            $timeout(function(){
                el.text(el.text().toUpperCase());
            });
        }
    }
});

Fiddle