Angularjs - ng-click function vs directive

Bod*_*ody 11 javascript angularjs angularjs-directive angularjs-ng-click

我不能决定在下面的情况下使用哪种方法.点击按钮时我正在尝试提醒.我可以用2种方法做到这一点.哪个是最佳做法,请告诉我原因?

方法1

<div ng-app="app">
  <button alert>directive</button>
</div>
Run Code Online (Sandbox Code Playgroud)
var app = angular.module('app', ['ngRoute']);

app
  .directive('alert', function(){
    return {

      link: function(scope, element, attr) {
            element.on('click', function(){
          alert('clicked');
        })
      }

    }
  })
Run Code Online (Sandbox Code Playgroud)

方法2

<div ng-app="app" ng-controller="MainCtrl">
  <button ng-click="go()">ng-click</button>  
</div>
Run Code Online (Sandbox Code Playgroud)
app.controller('MainCtrl', ['$scope', function($scope) {

  $scope.go = function() {
    alert('clicked');
  }
}]);
Run Code Online (Sandbox Code Playgroud)

谢谢你,乳山

jad*_*nda 11

让我用例子向你解释一下.

HTML

<div ng-app="myapp">
    <div ng-controller="MyCtrl1">
        <button ng-click="showAlert('hello')">Fist</button>
        <button ng-click="showConsole('hello')">for Fist one only</button>
        <button show-alert="first using directive">Fist with directive</button>
    </div>
    <div ng-controller="MyCtrl2">
        <button ng-click="showAlert('hello second')">Second</button>
        <button show-alert="first using directive">Second With directive</button>
    </div>
    <div ng-controller="MyCtrl3">
        <button ng-click="showAlert('hello third')">Third</button>
        <button show-alert="third using directive">third with directive</button>
    </div>
 </div>
Run Code Online (Sandbox Code Playgroud)

JS

var myApp = angular.module('myapp',[]);

myApp
    .controller('MyCtrl1', function ($scope) {
        $scope.showAlert = function (msg) {
            alert(msg);
        };
        $scope.showConsole = function (msg) {
            console.log(msg);
        };
    })
    .controller('MyCtrl2', function ($scope) {
        $scope.showAlert = function (msg) {
            alert(msg);
        };

    })
    .controller('MyCtrl3', function ($scope) {
        $scope.showAlert = function (msg) {
            alert(msg);
        };        
    })
    .directive('showAlert', function(){
        return{
            restrict: 'A',
            link: function(scope, ele, attr){
                var eventName = attr.evetName || 'click';
                var mas = attr.showAlert || 'just alert';
                ele.on(eventName, function(){
                   alert(mas); 
                });
            }
        };
    });
Run Code Online (Sandbox Code Playgroud)

JsFiddleLink

正如您在示例中show-alert="[MSG]"所看到的,与$scope.showAlert在每个控制器中直接使用相比,能够减少代码复制.所以在这种情况下,创建指令更好.

但是,如果$scope.showConsole只使用一次,我们不会在任何地方重复使用它.所以它可以直接在控制器内使用它.

即使.您还可以创建showConsole功能指令,如果您将来感觉它也会在其他地方使用.它完全没问题.这个决定完全取决于你的用例.