簡體   English   中英

自定義指令的角度控制器

[英]Angular Controller on Custom Directive

這是我的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>嗎?

后一種選擇對我來說很難看。

很高興聽到這種訪問方式,我已經嘗試過

<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>

然后我們可以訪問兩個控制器,但是當我們使用like

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

我們無法訪問SearchMasterController,它也未加載。

是的,您可以為指令使用其他控制器,但是有一些最佳實踐

當您要將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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM