无法在指令中使用服务方法;显示该方法的测试是在服务上定义的

时间:2015-02-02 11:27:57

标签: angularjs angularjs-directive angularjs-scope

我试图制作一个指令,以我喜欢的格式生成 Lorem Ipsum 文本。这就是我所拥有的:

angular.module('mock.text', [])
  .factory('TextGenerator', function() {
    var words = [/** lots of array elements (lorem ipsum text) **/];
    return {
      createWords: function(wordCount) {
        var wordCount = wordCount;
        var idx = Math.floor(Math.random() * 199);
        var sentence = words.slice(idx, wordCount);
        sentence.join(' ');
        sentence.charAt(0).toUpperCase();

        return sentence;
      }
    }
  })

  .directive('text', function(TextGenerator) {
    return {
      restrict: 'EA',
      link: function(scope, element, attrs) {
        var words = TextGenerator.createWords(Number(attrs['numWords']));
        scope.words = words;
      },
      scope: {},
      template: '<p> {{words}} </p>'
    }
  });

然后将其发送到主app模块:

angular.module('myApp', ['mock.text']);

我还有一个测试来检查服务是否正常工作:

describe('TextGenerator', function() {
    beforeEach(module('myApp'));

    it('should have a createWords method', function() {
        angular.mock.inject(function(TextGenerator) {
            expect(TextGenerator.createWords).toBeDefined();
        });
    });
});

上面的测试通过,但是当我尝试实际使用像这样的指令

<p text num-words="7"></p>

我改为在控制台中出错: undefined不是函数,它发生的行在指令定义中

var words = TextGenerator.createWords(Number(attrs['numWords']));

我尝试过其他方法试图找到问题的根源但没有运气。有人能解释一下这里发生了什么吗?

1 个答案:

答案 0 :(得分:0)

服务一切都很好,我按原样累了你的代码。 代码在sentence.charAt(0).toUpperCase();处突破 正确审核createWords方法。

相关问题