ngTagInput 通过指令调用时给出 javascript 控制台错误

问题描述 投票:0回答:1

我正在尝试在我的

[ngTagsInput][1]
项目中实现
angularjs
。以下是我的设置:

#js file
$scope.loadTags = function(query) {
        $scope.tags = [
            { text: 'just' },
            { text: 'some' },
            { text: 'cool' },
            { text: 'tags' }
          ]
        //return $http.get('/tags?query=' + query);
 }
 

在我看来(myview.html.haml)

  %tags-input{"ng-model" => "tags"}
    %auto-complete{:source => "loadTags($query)"}

等同于:

   <tags-input ng-model="tags">
        <auto-complete source="loadTags($query)"></auto-complete>
      </tags-input>

上面的代码是我从 ngTagInput 插件网站本身复制的。我正在使用 CDN 加载与插件网站中相同的版本。但是当我输入标签时,我在 JavaScript 控制台中收到以下错误:

TypeError: Cannot read property 'then' of undefined
    at http://cdnjs.cloudflare.com/ajax/libs/ng-tags-input/2.0.1/ng-tags-input.min.js:1:5150
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js:13777:28
    at completeOutstandingRequest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js:4236:10)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js:4537:7 

这看起来像是与承诺有关。 (我对 Angular.js 还很陌生,我只是猜测),但我想知道它在 website 中给出的示例中是如何工作的。

但是如果我在页面加载时加载标签,它就可以正常工作。这里可能出了什么问题?

编辑

@Pierre 评论后,我的新代码如下所示

我可能忘记了最重要的部分,我从

in controller
调用这个标签自动完成方法(
directive
)。

recipeform.tags
是我的模特

#haml form
 %tags-input{"ng-model" => "recipeform.tags"}
    %auto-complete{:source => "loadTags($query)"}

#js
$scope.loadTags = function(query) {
        var defer = $q.defer();
        defer.resolve([
            { text: 'just' },
            { text: 'some' },
            { text: 'cool' },
            { text: 'tags' }
            ]);
        return defer.promise;
        /*return [*/
            //{ text: 'just' },
            //{ text: 'some' },
            //{ text: 'cool' },
            //{ text: 'tags' }
        /*]*/
      }

两个 js 代码都给出与之前相同的错误。

javascript angularjs angular-directive ng-tags-input
1个回答
3
投票
 <auto-complete source="loadTags($query)"></auto-complete>

“source”是一个应该返回承诺的方法,它将用于返回标签。不要将它们注入到您的模型中...

$scope.loadTags = function(query) {
       return[
            { text: 'just' },
            { text: 'some' },
            { text: 'cool' },
            { text: 'tags' }
          ]
 }

应该可以。如果没有,则意味着该指令需要真正的承诺,那么您将需要这样做(但我认为您不需要走这么远):

$scope.loadTags = function(query) {
     var defer = $q.defer();
     defer.resolve([
            { text: 'just' },
            { text: 'some' },
            { text: 'cool' },
            { text: 'tags' }
          ]);
     return defer.promise;
 }
© www.soinside.com 2019 - 2024. All rights reserved.