如何将angularjs控制器拆分成块?

时间:2016-04-28 23:29:25

标签: angularjs refactoring

我对AngularJs很新,希望我能在这里得到一些帮助。下面我有两个非常相似的控制器。一个用于编辑项目,一个用于添加新项目。我想知道如何重构这段代码,以便为两个控制器重用大部分代码,或者只使用一个控制器。我最初尝试使用一个控制器,但新项目页面不允许我在字段中输入任何内容。我想因为没有像编辑那样的当前模型数据。

任何帮助都将不胜感激。

tplApp.controller('editController', function ($scope, $http, $routeParams){

    $scope.template = {};
    $scope.id = $routeParams.template_id;

    $http.get(baseUrl+'templates/get_template/'+$scope.id).success(function(data) {
        $scope.template = data;
    });

    $scope.bodyOptions = {
        plugins: 'link image code',
        toolbar: 'bold, italic, underline,  alignleft, aligncenter, alignright, alignjustify, styleselect, bullist, numlist, outdent, indent, removeformat, mybutton, code',
        height: 300,
        menubar: false,
        statusbar: false,
        setup: function(editor) {
            editor.addButton('mybutton', {
                type: 'menubutton',
                text: 'Variables',
                icon: false,
                menu: [
                    {text: 'Candidate Name', onclick: function() {editor.insertContent('%name%');}},
                    {text: 'Company Name', onclick: function() {editor.insertContent('%company-name%');}},
                    {text: 'Today\'s Date', onclick: function() {editor.insertContent('%date%');}},
                    {text: 'Your Name', onclick: function() {editor.insertContent('%your-name%');}},
                ]
            });
        }
    };

    $scope.saveTemplate = function() {
        $http({
            method  : 'POST',
            url     : baseUrl+'templates/save',
            data    : $.param($scope.template),  
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  
        })
        .success(function(data) {
            $scope.message = data.message;
            if (data.success) {
                console.log(data);
                $scope.templates = data.templates;
            }
        });
    };



});



tplApp.controller('addController', function ($scope, $http){

    $scope.template = {};

    $scope.bodyOptions = {
        plugins: 'link image code',
        toolbar: 'bold, italic, underline,  alignleft, aligncenter, alignright, alignjustify, styleselect, bullist, numlist, outdent, indent, removeformat, mybutton, code',
        height: 300,
        menubar: false,
        statusbar: false,
        setup: function(editor) {
            editor.addButton('mybutton', {
                type: 'menubutton',
                text: 'Variables',
                icon: false,
                menu: [
                    {text: 'Candidate Name', onclick: function() {editor.insertContent('%name%');}},
                    {text: 'Company Name', onclick: function() {editor.insertContent('%company-name%');}},
                    {text: 'Today\'s Date', onclick: function() {editor.insertContent('%date%');}},
                    {text: 'Your Name', onclick: function() {editor.insertContent('%your-name%');}},
                ]
            });
        }
    };

    $scope.saveTemplate = function() {
        $http({
            method  : 'POST',
            url     : baseUrl+'templates/save',
            data    : $.param($scope.template),  
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  
        })
        .success(function(data) {
            $scope.message = data.message;
            if (data.success) {
                console.log(data);
                $scope.templates = data.templates;
            }
        });
    };



});

3 个答案:

答案 0 :(得分:0)

您想要的是一项服务:https://docs.angularjs.org/guide/services您可以使用服务在整个应用中组织和共享代码

谷歌和/或在SO中查看更多信息。

答案 1 :(得分:0)

尝试这些更改。您将需要2个服务+ 2个控制器(saveTemplateService.jsbuildBodyOptionsService.js)。服务将注入控制器。

最后,不要忘记在模板/ html文件中添加每个服务的src

我认为它可能会更加减少(在控制器中没有$http的{​​{1}})但是因为我们在这里使用回调,所以我不确定。尝试一下;)。

它可能没有完全正常运行,因为我没有你所有的代码。但是调试应该解决它。

<强> saveTemplateService.js:

success

<强> buildBodyOptionsService.js:

app.factory('saveTemplateService', function ( baseUrl, $http ) {
    return $http({
                method  : 'POST',
                url     : baseUrl+'templates/save',
                data    : $.param($scope.template),  //fix these (injecting them like baseUrl)
                headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  
            });
});

<强> editController.js

app.factory('buildBodyOptionsService', function() {
     return {
         build: function ( editor ) { //maybe editor needs to be injected
            var output = {
                plugins: 'link image code',
                toolbar: 'bold, italic, underline,  alignleft, aligncenter, alignright, alignjustify, styleselect, bullist, numlist, outdent, indent, removeformat, mybutton, code',
                height: 300,
                menubar: false,
                statusbar: false,
                setup: function(editor) {
                    editor.addButton('mybutton', {
                        type: 'menubutton',
                        text: 'Variables',
                        icon: false,
                        menu: [
                            {text: 'Candidate Name', onclick: function() {editor.insertContent('%name%');}},    //  I dont like this functions here. There must be a better way to do this (ex: in a partial html with ng-click)
                            {text: 'Company Name', onclick: function() {editor.insertContent('%company-name%');}},
                            {text: 'Today\'s Date', onclick: function() {editor.insertContent('%date%');}},
                            {text: 'Your Name', onclick: function() {editor.insertContent('%your-name%');}},
                        ]
                    });
                }
            };
            return output; 
         }
     };
});

<强> addController.js

tplApp.controller('editController', function ($scope, saveTemplateService, buildBodyOptionsService) {
    $scope.template = {};

    $scope.id = $routeParams.template_id;
    $http.get(baseUrl+'templates/get_template/'+$scope.id)
            .success(function(data) {
                $scope.template = data;
    });

    // call 1st service
    $scope.bodyOptions = buildBodyOptionsService.build( editor );

    // call 2nd service
    $scope.saveTemplate = saveTemplateService.success( function(data) {
        $scope.message = data.message;
            if (data.success) {
                console.log(data); //use $log.info() instead
                $scope.templates = data.templates;
            }
    });
});

请查看以下链接以获取更多信息:

答案 2 :(得分:0)

我可能会将所有内容都放在一个服务中(templateService)。我不确定bodyOption是否属于那里但是现在我只是把它放在那里。然后我将加载/保存模板功能移动到服务。

你可以做更多,例如,你可以设置$ scope.templateService = templateService,并在你的html中直接使用templateService.bodyOptions / templates。

此外,您可以将save.success从控制器移动到服务中。

<a href="#" onclick="void('Cut');"></a>

理想情况下,您的控制器可能如下所示:

tplApp.service('templateService', function($http, $routeParams) {

var self = this;
this.template = {};

this.loadTemplate = function() {
   $http.get(baseUrl+'templates/get_template/' + $routeParams.template_id)
       .success(function(data) {
           self.template = data;
       });
};

this.saveTemplate = function() {
    return $http({
        method: 'POST',
        url: baseUrl + 'templates/save',
        data: $.param(self.template),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });
};

this.bodyOptions = {
    plugins: 'link image code',
    toolbar: 'bold, italic, underline,  alignleft, aligncenter, alignright, alignjustify, styleselect, bullist, numlist, outdent, indent, removeformat, mybutton, code',
    height: 300,
    menubar: false,
    statusbar: false,
    setup: function(editor) {
        editor.addButton('mybutton', {
            type: 'menubutton',
            text: 'Variables',
            icon: false,
            menu: [
                {text: 'Candidate Name', onclick: function() {editor.insertContent('%name%');}},
                {text: 'Company Name', onclick: function() {editor.insertContent('%company-name%');}},
                {text: 'Today\'s Date', onclick: function() {editor.insertContent('%date%');}},
                {text: 'Your Name', onclick: function() {editor.insertContent('%your-name%');}},
            ]
        });
    }
};
});

tplApp.controller('editAndAddController', function ($scope, templateService){
$scope.template = templateService.template;
$scope.bodyOptions = templateService.bodyOptions;

if(edit) {
    templateService.loadTemplate();
}

$scope.saveTemplate = function() {
    templateService.saveTemplate()
        .success(function(data) {
            $scope.message = data.message;
            if (data.success) {
                console.log(data);
                $scope.templates = data.templates;
            }
        });
};
});
  

抬起头来!这只是示例,代码未经过测试!