自定义指令的角度控制器

时间:2015-10-27 08:09:04

标签: javascript angularjs

这是我的controllers.js文件

(function(ctx,angular){
    'use strict';
    angular.module('app.controllers')

    .controller('SearchMasterController',['$scope',function($scope){
        //My Code
    }]);

})(window, angular);

这是我的directives.js文件

(function(ctx,angular){
    function ControllerFunction(){
        //My Controller Code
    }
    var directiveConfig = {
        restrict:'E',
        templateUrl:'path/to/acco.html',
        controller: ControllerFunction
    }

    angular.module('app.directives')
    .directive('acco', function(){
        return directiveConfig;
    });
})(window, angular);

现在我的问题是,我可以将这个acco指令与一些不同的控制器一起使用。理想情况下,有没有办法让它像

一样运作

<acco ng-controller="SearchMasterController"></acco>

我试过了,

<acco>
    <div ng-controller="SearchMasterController"></div>
</acco>

它似乎有效。

是否可以使用

<acco ng-controller="SearchMasterController"></acco>

后一种选择看起来很难看。

2 个答案:

答案 0 :(得分:1)

很高兴听到这种类型的访问,我试过

<acco>hi{{name1}}
    <div ng-controller="SearchMasterController">{{name1}}</div>
</acco>
<acco ng-controller="SearchMasterController">{{name1}}</acco>
<script>
            angular.module('myApp', [])
                    .controller('SearchMasterController', ['$scope', function ($scope) {
                            //My Code
                            console.log("search");
                            $scope.name1 = 'james';
                        }])
                    .directive('acco', function () {
                        return{
                            restrict: 'E',
                            templateUrl: 'acco.html',
                            controller: function($scope) {
                                //My Controller Code
                                console.log("cntrlr fn");
                                $scope.name1 = 'semaj';
                            }
                        };
                    });
</script>

@我输出的时间是

cntrlr fn
search
cntrlr fn           

表示我们使用的是

<acco>hi{{name1}}
    <div ng-controller="SearchMasterController">{{name1}}</div>
</acco>

然后我们可以访问两个控制器,但是当我们使用

<acco ng-controller="SearchMasterController">{{name1}}</acco>

我们无法访问SearchMasterController并且它也没有加载..

答案 1 :(得分:0)

是的,你可以为你的指令使用一些不同的控制器,但有一些best practice

  

如果要将API公开给其他指令,请使用控制器。否则使用链接。

您尝试使用控制器的方式没有多大意义

<!--here acco and ng-controller both are directives,
    in your directive's 'ControllerFunction' and ng-controller's 'SearchMasterController'
    has the same controll (scope) for 'acco' rendered html.
    In that case your directive's controller overrite ng-controller functionality.
    So leave 'ng-controller',
    if you need any functionality in your directive
    then pass those functionality using =,&,@-->

<acco ng-controller="SearchMasterController"></acco>