2013-03-01 3 views
3

AngularJS에 시도해보십시오. 나는 아주 간단하게하려고하지만 좋은 방법으로하고 싶습니다.범위 상속 대신 AngularJS 시계 서비스 값이 변경됨

각 항목의 이름과 수량을 표시하는 표에서 항목 목록을 받았습니다. 테이블 아래에 양식이 있습니다.

테이블에서 항목 이름을 클릭하면 해당 항목을 양식을 통해 업데이트 할 수 있습니다. 그것이 아닌,

function ItemListController($scope){ 
    $scope.items = [{name:'item1', quantity:10}, {name:'item2', quantity:5}]; 

    $scope.selectCurrentItem = function(currentItem) { 
     $scope.currentItem = currentItem; 
    } 
} 

function ItemFormController($scope){ 
    $scope.$watch('currentItem', function() { 
     $scope.item = $scope.currentItem; 
    }); 
} 

을하지만 일부 항목에 읽을 수있다 :

<tr ng-repeat="item in items"> 
    <td><a href="#" ng-click="selectCurrentItem(item)">{{item.name}}</a></td> 
    <td>{{item.quantity}}</td> 
</tr> 

컨트롤러 :

나는 http://jsfiddle.net/5cRte/1/

보기 바이올린과 같이 범위 상속 일을 달성 이 방법으로 컨트롤러 범위를 연결하는 것이 좋으며, 컨트롤러간에 공유되는 변수를 저장하는 서비스를 사용하지 않는 것이 좋습니다.

정적 변수를 서비스에 넣고 다른 컨트롤러에서 검색 할 수는 있지만 서비스 변수에서 작동하지 않는 시계와 같이 테이블에서 항목을 클릭 할 때 해당 변수를 업데이트 할 수 없습니다. 이 힌트가 있니? 사전에

감사

답변

3

내가이 최적인지 모르지만 이것은 내가 가지고 올 수

angular.module('myApp', []); 

angular.module('myApp').factory('myService', function(){ 
    var items = [{name:'item1', quantity:10}, {name:'item2', quantity:5}, {name:'item3', quantity:50}]; 
    var current = {}; 
    return { 
     getItems: function(){ 
      return items; 
     }, 

     setCurrentItem: function(item){ 
      current.item = item; 
     }, 

     removeCurrentItem: function(){ 
      delete current.item; 
     }, 

     getCurrent: function(){ 
      return current; 
     } 
    } 
}); 

function ItemListController($scope, myService){ 
    $scope.items = myService.getItems(); 

    $scope.selectCurrentItem = function(currentItem) { 
     myService.setCurrentItem(currentItem); 
    } 
} 

function ItemFormController($scope, myService){ 
    $scope.current = myService.getCurrent(); 
} 

데모 : Fiddle

+0

안녕, 그것이 내가 무엇 해결하기 위해 온다 하려고하는 것. getCurrentItem 대신 getCurrentItem을 사용하면 처음에 current.item을 반환하는 이유는 알 수 없습니다. –

+2

@StephaneToussaint : ItemFormController의 스코프에 전류를 설정하면 현재 변경 사항 (이 예제에서는 current.item 변경)을보고 있기 때문입니다. 그러나 current.item을 범위에 직접 설정하면 범위가 변경 사항을 잡을 수 없습니다. 기술적으로 다른 객체를 변수로 설정하지만 컨트롤러 범위가 아닙니다 (변수 참조가 자바 스크립트에서 지원되지 않음). 예제가 더 잘 설명 될 수 있기를 바랍니다. http://jsfiddle.net/q5BQt/ :) – JakubKnejzlik

+0

의견을 보내 주셔서 감사합니다. 그 사실은 분명히 분명합니다. –