在指令中的方法之间共享变量的最佳实践

时间:2016-01-19 14:45:25

标签: angularjs

假设我有两个方法的简单指令。在可读性方面,我希望将所有共享变量放在链接函数之上。

最好的方法是什么?

angular.module('myApp', [])
 .directive('myCustomer', function() {
  return {
    restrict: 'E',
    templateUrl: 'my-customer.html'
    link: link
  };

  function link(scope,element,attrs){

    var myCustomer = { // same name as directive so it's clear it's a global object
      myCompany: "stackoverflow",
      myCar: "tesla"
    };

    function funcA(){
      config.myCar = "ferrari";
    } 

    function funkB(){
      alert(config.myCar);
    }

    funcA();
    funcB();

  }

});

那会是一个好习惯吗?我要求更复杂的情况,比如异步初始化“myCustomer”键。

2 个答案:

答案 0 :(得分:2)

只需使用指令 scope

angular.module('myApp', []).directive('myCustomer', function() {
    return {
        restrict: 'E',
        templateUrl: 'my-customer.html',
        link: function(scope, element, attrs) {

            scope.myCustomer = {
                myCompany: "stackoverflow",
                myCar: "tesla"
            }

            function funcA() {
                scope.myCustomer.myCar = "ferrari";
            } 

            function funcB() {
                // should be 'ferrari'
                alert(scope.myCustomer.myCar);
            }

            funcA();
            funcB();

         }
    };

});

答案 1 :(得分:0)

angular.module('myApp', [])
    .constant('BASE_API_URL', 'http://api.example.com')
    .service('customerService', function customerService ($http, BASE_API_URL) {
        return {
            getCustomer: getCustomer
        };

        function getCustomer() {
            // Returns a promise
            $http.get(BASE_API_URL + '/customer');
        }
    })
    .controller('mycontroller', function ($scope, customerService) {
        $scope.customer = null;

        customerService.getCustomer().success(function (customer) {
             $scope.customer = customer;
        });
    })
    .directive('myCustomer', function() {
        return {
            restrict: 'E',
            templateUrl: 'my-customer.html',
            scope: {
                customer: '=',
            },
            link: link
        };

        function link(scope, element, attrs) {

            // $scope.customer is the customer object

            function funcA() {
                config.myCar = "ferrari";
            }

            function funkB() {
                alert(config.myCar);
            }

            funcA();
            funcB();

        }
    });

<my-customer ng-if="customer" customer="customer"></my-customer>