Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 重构AngularJS代码-提取函数_Javascript_Angularjs - Fatal编程技术网

Javascript 重构AngularJS代码-提取函数

Javascript 重构AngularJS代码-提取函数,javascript,angularjs,Javascript,Angularjs,我正在开发AngularJS应用程序。该应用程序严重依赖模块。我有一个模块,其中有一个控制器和一个指令。该模块如下所示: angular.module('myApp.component', []) .controller('ShellCtrl', function ($scope, $location, $rootScope, $gustoAreas) { $scope.myVariable = false; }) .directive('myDirect

我正在开发AngularJS应用程序。该应用程序严重依赖模块。我有一个模块,其中有一个控制器和一个指令。该模块如下所示:

angular.module('myApp.component', [])
    .controller('ShellCtrl', function ($scope, $location, $rootScope, $gustoAreas) {
        $scope.myVariable = false;
    })
    .directive('myDirective', function(){
        return {
            restrict: 'E',
            replace: true,
            template: function() {
                return '<div>Some HTML Goes Here</div>';
            },
            scope: true
        };
    })
;
    .directive('myDirective', function(){
        return {
            restrict: 'E',
            replace: true,
            template: generateTemplate(),
            scope: true
        };
    })
我对JavaScript语法有点生疏。我的问题是,我现在在哪里定义
generateTemplate
?我怎么称呼它?我是否需要使用
generateTemplate()
generateTemplate
(带或不带括号)


谢谢你的帮助

我认为您可以将
generateTemplate
代码提取到服务中。假设
generateTemplate()
返回一个包含DOM的字符串,则必须用括号调用它


您可能也对
templateUrl
选项感兴趣,因此,您可以使用单独的HTML/模板文件来使代码更加模块化,而不是使用硬编码的
template

您可以在全局范围内的任意位置定义generateTemplate,如下所示: 函数generateTemplate(){…} 之前或之后都不重要,因为之前会编译它。
不应使用括号,因为它会触发函数执行,而只需要函数引用。

最简单的方法是定义如下值:

angular.module('myApp.component', [])
    .value('generateTemplate', '<div>Some HTML Goes Here</div>');
angular.module('myApp.component', [])
    .constant('generateTemplate', '<div>Some HTML Goes Here</div>');

generateTemplate是否返回函数或字符串(如提供的示例中传入参数的函数)。在第一种情况下(不太可能),应使用括号!
.directive('myDirective', function(generalTemplate){
    return {
        restrict: 'E',
        replace: true,
        template: generalTemplate,
        scope: true
    };
})