繁体   English   中英

如何在指令控制器中注入依赖项

[英]How to inject dependencies in directive controller

我在我的角度应用程序中使用ui-router。

下面的应用程序不是实际的应用程序,而是代表我的问题的最小型小型应用程序。 任何帮助表示赞赏。

我在声明这样的路线时使用了决心。

以下是需要解决的功能

angular.module('routerApp').formItemModel = function(){
  return {
    test: function(){
      return {name: 'Jenish'}
    }
  };
}

和路由定义是这样的:

$stateProvider.state('home.list', {
    url: '/list',
    templateUrl: 'partial-home-list.html',
    resolve: $injector.instantiate(angular.module("routerApp").formItemModel, {}),
    controller: function($scope, test) {
        $scope.dogs = ['Bernese', 'Husky', 'Goldendoodle'];
        $scope.name = test.name;
        }
    })

如果我确实有这样的html,则解析器和应用程序将完美运行:( partial-home-list.html

<ul>
    <li ng-repeat="dog in dogs">{{ dog }}</li>
</ul>
name: {{name}}

但是我处于需要将此名称移至指令的情况,因此我创建了这样的测试指令。

(function () {
    'use strict';

    angular.module('routerApp').directive('test', function () {
        var linker = function (scope, element) {

        }

        var controllerFunction = function ($scope, test) { //How to inject test here as it reports error **Unknown provider: testProvider <- test**
            $scope.name = test.name;
        }

        return {
            controller: controllerFunction,
            templateUrl: 'test.html',
            restrict: 'E',
            link: linker
        };
    });

}())

如下更新了partial-home-list.html

<ul>
    <li ng-repeat="dog in dogs">{{ dog }}</li>
</ul>
name: {{name}}
<test></test>

对于上面的示例, 很麻烦。

您不能在指令中插入以状态解析的数据,因为指令可以在ui-view外部使用,因此插入将无效。 您应将数据从控制器传递到视图,如下所示:

scope: {
    data: '='
}

视图:

<test data="test"></test>

朋克

您也可以对问题使用transclude选项。 像这样

从您的范围中删除控制器,然后添加

transclude:true

指令中的选项。

<div>
  <div>
      <b>This is directive content with </b>
  </div>
  <ng-transclude></ng-transclude>
</div>

然后你可以像这样使用指令

<test>This is the name {{name}}</test>

因此,名称将从外部范围而不是指令范围获取。

朋克

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM