我正在尝试创建一个简单的指令工作,它将简单地返回大写文本。文本通过绑定从控制器传递。
基本理念是:
<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');
});
});
});
答案 0 :(得分:0)
使用$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 强>