为AngularJs中的函数设置默认值

时间:2016-08-11 04:27:51

标签: angularjs

我想为函数设置默认行为。如果函数被传递,它应该执行该方法,否则应采用默认方法。以下是我正在尝试的代码段

module.directive("zoll",function(){
  return{
    restrict:"EAC",
    scope:{
        displayName: "@",
        buttonClick: "&"
    },
    template:"<input type='button' id='cncl' value={{displayName}} ng-click='buttonClick()'>",
    controller:function($scope){
        console.log($scope.buttonClick);

        if($scope.buttonClick === undefined){
            $scope.buttonClick = function () {
                alert("Inside Button");
            }
        }

    }
  }
});

1 个答案:

答案 0 :(得分:0)

你走了。考虑将controller函数更改为link函数,以便我们可以使用$attr(指令的属性)检查是否提供了回调函数。

带范围的解决方案不起作用,因为Angular在您指定'&'时始终指定一个函数。请在此处查看:https://github.com/angular/angular.js/blob/v1.5.8/src/ng/compile.js#L3377

&#13;
&#13;
var module = angular.module("sa", []);

module.controller("FooController", function($scope) {

  $scope.callMe = function() {
    alert("you called me");
  };
});

module.directive("zoll", function() {
  return {
    restrict: "EAC",
    scope: {
      displayName: "@",
      buttonClick: '&'
    },
    template: "<input type='button' value={{displayName}} ng-click='buttonClick()'>",
    link: function($scope, element, $attr) {
      if (!$attr.buttonClick) {
        $scope.buttonClick = function() {
          alert("Inside Button");
        }
      }
    }
  }
});
&#13;
input {
  width: 100%;
  padding: 20px;
  margin-bottom: 15px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="FooController">
  <zoll display-name="1st Button"></zoll>
  <br>2nd button with passed function
  <zoll display-name="2nd Button" button-click="callMe()"></zoll>
</div>
&#13;
&#13;
&#13;