【问题标题】:complex service creation with ngTagsInput使用 ngTagsInput 创建复杂的服务
【发布时间】:2024-03-09 09:40:01
【问题描述】:

我正在用我的博客实现ngTagsInput,以便在添加或编辑新帖子时,用户可以添加现有的或他们自己的标签。

我的博客使用可以通过工厂访问的 firebase 数据源:

 servicesModule.factory("postsDB", function($resource){
    return $resource("https://datasource.firebaseio.com/Posts.json", {
        id: "@id"
     },
     {
         update: {
             method: "PUT"
         },
         query: {
           method: 'GET',
          isArray: false }
    });
});

因为 ngTagsInput 函数需要在其他控制器中使用,所以我想将它变成一个服务,因为标签字段在订单表单中的引用方式不同。 HTML 如下所示:

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

我想为 ngTagsInput 创建一个服务,该服务引用我上面的其他服务 (postsDB)。我一直在尝试使用以下代码:

 servicesModule.factory ( 'AddTags' , function($scope, $http, postsDB) {
   var myTags = '';
    var myTags = $firebaseArray(postsDB.child('Tags'));

            function loadTags (query) {
                 return $http.get('/Tags?query=' + query);
            };
    });

在我的控制器中:

controllersModule.controller('AddPostCtrl', ["$scope", '$location', '$firebaseArray', '$sce', 'postsDB', 'AddTags',  function($scope, $location, $firebaseArray , $sce, postsDB, AddTags){
           AddTags(function(myTags){
             $scope.post.Tags = myTags;
           });

但是,我收到以下错误:

Error: [$injector:unpr] Unknown provider: $scopeProvider &lt;- $scope &lt;- AddTags

而且它似乎没有将 AddTags 识别为工厂服务。如何获取目标 $scope.repeatevariable.Tags 以映射到 Firebase 源中的 myTags 键?

编辑 - 引发错误:

ervicesModule.factory ( 'InputTags' , function($http, postsDB, $firebaseArray) {
  var myTags = '';
   var myTags = $firebaseArray(postsDB.child('Tags'));

           function loadTags (query) {
                return $http.get('/tags?query=' + query);
           };
   });

【问题讨论】:

  • 这可能是因为 $scope 在服务和工厂中不能作为直接注入使用。
  • 那么如何将一个注入另一个?

标签: javascript angularjs angular-services ng-tags-input


【解决方案1】:

$scope在工厂内不可用。在工厂中使用 $scope 是没有意义的。来自 Angular 文档:Scope is the glue between application controller and the view.

【讨论】:

    【解决方案2】:

    很明显,您甚至没有在工厂中使用 $scope 对象。因此,只需将其从您的工厂构造函数依赖项中删除即可。

    【讨论】:

    • 请看我上面的编辑。我已删除 $scope 但现在我收到以下错误:“TypeError:postsDB.child 不是函数”。我正在尝试访问帖子>帖子的子“标签”。它应该返回一个 JSON 数组“Tags”:[tag, tag1, tag2]。我这样做对吗?