2014-01-10 6 views
1

사용자는 컨트롤러에서 사용자가 템플릿에서 조작 할 수있는 범위에 노출 된 모델을 가지고 있습니다. 템플릿의 클릭 핸들러가 호출 할 모델에서 작동하는 컨트롤러의 함수. 왜 어느 것을 선호하는 경우와 :

  • 모델로 함수를 호출 템플릿
  • 을 통해 인수로 모델과 함수를 호출 범위

Working fiddle.

에 이상 폐쇄

편집 : John Lindquist의 this video에서 그는 첫 번째 양식의 사용을 옹호하며 테스트가 더 쉬워 진다고 주장합니다. 컨트롤러 메서드에 대한 테스트가 인수를 전달할 때 더 읽기 쉽다는 점에서 나는 그것에 동의 할 수 있습니다.

템플릿 :

<div ng-app="myApp"> 
    <div class="container demo-container" ng-controller="MyCtrl"> 

     <label for="model_input"> 
      Model: 
      <input type="text" class="form-control" ng-model="model" name="model_input"/> 
     </label> 

     <p> 
      Invoke function with <strong>'{{model}}'</strong> explicitly through template 
     </p> 
     <button class="btn btn-primary" ng-click="fn_through_tpl(model)"> 
      Click 
     </button> 

     <p> 
      Invoke function with <strong>'{{model}}'</strong> implicitly through controller 
     </p> 
     <button class="btn btn-primary" ng-click="fn_through_ctrl()"> 
      Click 
     </button> 

    </div> 
</div> 

컨트롤러 : 당신의 예에서

angular.module('myApp', []) 

.controller('MyCtrl', function ($scope) { 
    $scope.model = "my model"; 

    $scope.fn_through_tpl = function (model) { 
     alert(model + " through template!"); 
    } 

    $scope.fn_through_ctrl = function() { 
     alert($scope.model + " through $scope!"); 
    } 
}); 

답변

2

, 나는 후자 권 해드립니다 - 당신이 컨트롤러를 통해 함수를 호출 무엇을. 양방향 데이터 바인딩을 사용하면 이미 업데이트 된 모델을 다시 전달할 필요가 없습니다. 그것은 독자에게 중복되고 혼란 스럽습니다. 대신 모델에서 작동하는 컨트롤러에서 동작을 호출하십시오.

이전 패턴은 모델이 배열에 있거나 포함되어 있고 배열 요소에서 작동하는 컨트롤러 동작을 노출하고자 할 때 적절하다고 생각합니다. 예 :

<div ng-repeat="comment in post.comments"> 
    {{ comment.message }} 
    <button ng-click="deleteComment(comment)">Delete comment</button> 
</div> 
+0

첫 번째 양식이 적절한 경우의 좋은 예입니다. – yangmillstheory

관련 문제