角度和普通的javascript函数,最佳实践

时间:2016-11-18 17:40:51

标签: javascript angularjs

这种向(角度)脚本添加函数的方式之间是否有任何差异(可能在性能上),或者它们本质上是等价的:

选项1:控制器内的功能

link: function(scope, element, attrs){
           element.on('click', function(e) {
                if(scope.isChecked)
              {
                console.log('if');
                $uibModal.open({
                        animation: true,
                    backdrop: 'static',
                    keyboard: false,
                    templateUrl: 'modal.html',
                    controller: "ModalController"
                });
              }
              else
              {
                console.log('else ');
                scope.clickMe();
              }
           });

选项2:控制器外的功能

AngularApp.component('component', {
    templateUrl: '/domain/app/component.html'
    , controller: function ($scope,$rootScope,api) {

        $scope.var = false;
        getBackendData();

        //get data about available io_engines from the backend
        function getBackendData() {
            console.log("loading backend data...");            
            api.get().then(
                function (response) {                   
                    console.log("Backend data loaded.");
                })
                .catch(function (err) {
                    console.log("Error getting data from backend");
                    console.log(err);
                });
        }
   }

});

我(想)理解第二个选项中的 AngularApp.component('component', { templateUrl: '/domain/app/component.html' , controller: function ($scope,$rootScope,api) { $scope.var = false; getBackendData(); } }); //get data about available io_engines from the backend function getBackendData() { console.log("loading backend data..."); api.get().then( function (response) { console.log("Backend data loaded."); }) .catch(function (err) { console.log("Error getting data from backend"); console.log(err); }); } 成为一个全局函数,但我不太清楚其含义。

2 个答案:

答案 0 :(得分:2)

如果在组件中定义一个函数,每个组件实例将有一个函数定义,因此理论上它将占用更多内存。

在第二个示例中,每个应用程序只有一个函数。

但这种差异实际上是学术性的。这里的更大的问题是这些函数应该在(或作为)服务中定义,所以它们可以是:

  • 测试
  • 可能在其他地方重复使用
  • 在组件测试中嘲笑

答案 1 :(得分:1)

选项1更好,因为您没有污染全局范围。让我们说这不是一个好习惯。我建议你按照Todd Motto这样的风格指南:

https://github.com/toddmotto/angular-styleguide/tree/angular-old-es5