angularjs ngTagInput在通过指令调用时给出JavaScript控制台错误

nimxete2  于 6个月前  发布在  Angular
关注(0)|答案(1)|浏览(54)

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

#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


它看起来像是与promise有关的东西(我对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代码给予与前面相同的错误。

rkttyhzu

rkttyhzu1#

<auto-complete source="loadTags($query)"></auto-complete>

字符串
“source”是一个应该返回promise的方法,它将被用来返回标签。而不是将它们注入到你的模型中。

$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;
 }

相关问题