Angularjs - ng-click function vs directive

时间:2015-05-12 07:58:23

标签: javascript angularjs angularjs-directive angularjs-ng-click

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

方法1

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

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

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

    }
  })

方法2

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

  $scope.go = function() {
    alert('clicked');
  }
}]);

谢谢你, 乳山

2 个答案:

答案 0 :(得分:11)

让我用例子向你解释。

HTML

private void leerXml() {
    //Es necesario para utilizar la clase XMLPullParser
    XmlPullParserFactory factory;
    XmlPullParser xml;
    //Variable para los eventos
    int evento;
    boolean titulo;
    ArrayList<String> titulos;
    //Puedo leer el titulo?
    titulo = false;
    titulos = new ArrayList<String>();
    try {
        factory = XmlPullParserFactory.newInstance();
        xml=factory.newPullParser();
        //obtenemos la URL
        xml.setInput(url.openStream(),"UTF-8");

        evento = xml.getEventType();
        //Leer cada uno de los eventos hasta el final
        while (evento != XmlPullParser.END_DOCUMENT){
            switch(evento){
                case XmlPullParser.START_TAG:
                    if(xml.getName().equals("titulo")){
                        titulo = true;
                    }
                    break;
                case  XmlPullParser.TEXT:
                    if(titulo = true){
                        titulos.add(xml.getText());
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if(xml.getName().equals("titulo")) {
                        titulo = false;
                    }
                    break;
            }
            evento = xml.next();
        }

        titulares = new String[titulos.size()];
        for (int i = 0; i< titulos.size(); i++){
            titulares[i] = titulos.get(i);
        }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
        e.printStackTrace();
    }

}

JS

<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>

JsFiddleLink

正如您在示例中所看到的那样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); }); } }; }); 能够减少代码复制,而不是在每个控制器中直接使用show-alert="[MSG]"。所以在这种情况下,创建指令更好。

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

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

答案 1 :(得分:2)

如果所有元素都必须在click事件上运行相同的函数,那么将它作为指令是一个好主意。否则使用ngClick。创建一个指令然后传递一个单击处理函数就是重新实现同样的事情。