2013-02-17 15 views
14

Prosty przykład: Mam textarea i chcę zapewnić dodatkową zachowanie do niego: coś na enter klucz i przejść do następnej linii na shift + enterJak obserwować zdarzenia niestandardowe w AngularJS?

Przypuszczam, że powinienem zapewnić dodatkową dyrektywę dodać, że zachowanie. I zrobiłem to: http://jsbin.com/oruvuy/1/edit

P.S. Jedna rzecz hacka wydaje mi się dziwna: ręcznie wywołuję $digest(). Czy to jest w porządku? jakieś pomysły?

JS:

angular.module('Chat', []) 
    .directive('enterSubmit', function() { 
    return { 
     restrict: 'A', 
     link: function (scope, element, attrs) { 
     var submit; 

     $(element).on({ 
      keydown: function (e) { 
      submit = false; 

      if (e.which === 13 && !e.shiftKey) { 
       submit = true; 
       e.preventDefault(); 
      } 
      }, 

      keyup: function() { 
      if (submit) { 
       scope.$eval(attrs.enterSubmit); 

       // flush model changes manually 
       scope.$digest(); 
      } 
      } 
     }); 
     } 
    }; 
    }); 

function ChatCtrl($scope) { 
    $scope.messages = [{ 
    text: 'Sample Message', 
    datetime: new Date() 
    }]; 

    $scope.add = function() { 
    $scope.messages.push({ 
     text: $scope.message, 
     datetime: new Date() 
    }); 
    $scope.message = ''; 
    }; 

    $scope.message = ''; 
} 
<body ng-controller="ChatCtrl"> 

    <h1>Leave message:</h1> 
    <form> 
    <div class='hint'>Click &lt;Enter&gt; to submit :)</div> 
    <textarea 
     cols="30" 
     rows="5" 
     ng-model="message" 
     enter-submit='add()' 
    ></textarea> 
    <br /> 
    <button type="submit" ng-click="add()">Send message!</button> 
    </form> 

    <h3>Messages list:</h3> 
    <table> 
    <tr> 
     <th>Text</th> 
     <th>Date</th> 
    </tr> 
    <tr ng-repeat="message in messages"> 
     <td class='text'>{{message.text}}</td> 
     <td class='date'>{{message.datetime | date:"HH:mm:ss"}}</td> 
    </tr> 
    </table> 

</body> 

Ale czy jest to poprawny sposób to zrobić?

Odpowiedz

12

Tak, wiążące zdarzenia w funkcji łączenia dyrektywy są dokładnie tym, co chcesz zrobić.

Wywołanie $ digest nie jest hacky - wiadomości z przykładu są dodawane do modelu pod numerem keyup, a Angular nie przetrawi tych zmian, dopóki coś im nie powie. Zostanie on przetrawiony na następnym keydown, ale ponieważ potrzebujesz $ digest po twoim keyup, musisz wywołać to ręcznie.

+0

Świetnie, dziękuję za wyjaśnienia. Ale nie zrozumiano mnie na temat wydarzeń. AngularJS nasłuchuje wszystkich zdarzeń na stronie, a następnie sprawdza stan wszystkich obiektów? Czy jest jakiś zrozumiały artykuł na ten temat? Czytałem o tym w AngularJS, ale trudno to szybko zrozumieć. – ValeriiVasin

+0

Polecam [to pytanie StackOverflow] (http://stackoverflow.com/questions/12463902/how-does-the-binding-and-digesting-work-in-angularjs) jako dobry odnośnik. – jingman

Powiązane problemy