javascript - 自定义指令上的 Angular Controller

标签 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指令与一些不同的 Controller 。理想情况下,有什么办法让它像这样工作

<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           

意味着如果我们使用like

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

然后我们就可以访问两个 Controller ,但是当我们使用 like 时

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

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

关于javascript - 自定义指令上的 Angular Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33362698/

相关文章:

javascript - Angular.js $watch 表单/表单输入有效性

angularjs - 如何使用 ng-model 了解复选框的值

javascript - 使用 javascript 从 WordPress 页面读取 HTML

javascript - 跟踪复选框状态并为 ng-model 使用多个数据

javascript - 从 json 获取值到 angularjs 对象

javascript - Highcharts csv 导出问题

javascript - Jquery表单验证不可见字段

javascript - 从一开始就删除一个字符哈希/井号

javascript - JQuery 步骤 : How to show/hide an additional step based on user input

javascript - 将 vtype 添加到网格 EXT-JS 中的列