解析指令AngularJS

时间:2016-01-28 12:48:32

标签: javascript angularjs

我如何在指令中的config中使用像resolve这样的东西? 我有这样的代码:

angular.module('config', ['ngRoute', 'resources.params'])

.config(['$routeProvider', function($routeProvider) {
    'use strict';
    $routeProvider
        .when('/config',{
            templateUrl: 'templates/config/config.tpl.html',
            controller: 'ConfigCtrl',
            resolve: {
                params: ['Params', '$route',
                    function(Params, $route) {
                        if ($route.current.params.skey)
                            return Params.get($route.current.params.skey);
                        else
                            return null;
                    }
                ]
            },
            reloadOnSearch: true
        });
    }
])


.controller('ConfigCtrl', ['$scope','$route','$routeParams', 'params','Params',
   function($scope,$route,$routeParams,params,Params){
           'use strict';

我可以在我的控制器中使用“params”,因为我在我的.config中写了“params:[...” 但现在我想在我的指令中使用这个“params”:

.directive('mapsysitem', ['$location', '$routeParams', '$freshmark',
    function($location, $routeParams, $freshmark) {
        'use strict';

        return {
            restrict: 'E',
            require: '^mapsyslist',
            scope: {
                zoomlist: '@',
                item: '=',
                skey: '=',
                select: '&'
            },
            replace: true,
            templateUrl: 'templates/map/mapsysitem.tpl.html',

            controller: ['$element', '$scope', 'System','$filter','Params',
                function($element, $scope, System, $filter, Params) {
                    .....
            }]

       };
}]);

如果我将“params”添加到控制器选项中,我将有“Unknown provider:paramsProvider< - params”。我怎么能解决这个问题?想要你。

2 个答案:

答案 0 :(得分:0)

由于您在指令中使用了隔离范围,因此需要将该参数作为指令节点中的属性传递

在app controller中设置范围

.controller('ConfigCtrl', ['$scope','$route','$routeParams','params','Params',
function($scope,$route,$routeParams,params,Params){
       $scope.myParams=Params

然后将$ scope.myParams传递给指令

<mapsysitem param='myParams'></mapsysitem>

然后在范围内创建双向绑定

            scope: {
              param:'='     
            },

然后你就可以在指令控制器中使用它了

controller: ['$element', '$scope', 'System','$filter',
            function($element, $scope, System, $filter ) {
                 var myParams= scope.param

答案 1 :(得分:-1)

我不认为您可以获取指令控制器的范围或属性值,因此如果您不能使用服务(或者可能是$ rootScope)来共享这些值(并注意变化)。

否则您可以使用链接功能。您可以在此处访问范围和属性。以下是关于控制器/链接功能的角度站点的引用:

  

最佳实践:当您希望将API公开给其他指令时,请使用控制器。否则使用链接。

这意味着&#34;使用链接功能,除非您确定需要控制器&#34;。

请参阅https://docs.angularjs.org/guide/directive