3

AngularJS を試してみました。私は非常に単純なことをしようとしていますが、良い方法でやりたいと思っています。

各アイテムの名前と数量を表示するテーブルにアイテムのリストを取得しました。テーブルの下にフォームがあります。

テーブルからアイテム名をクリックすると、指定されたアイテムをフォームから更新できるようにしたいと思います。

フィドルhttp://jsfiddle.net/5cRte/1/のように、スコープの継承で物事を行うことができます

意見 :

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

コントローラー:

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; 
    });
}

しかし、いくつかのトピックを読んだことがありますが、このようにコントローラーのスコープを結合することはお勧めできません。できれば、サービスを使用してコントローラー間で共有される変数を保存したくありません。

静的変数をサービスに配置して別のコントローラーで取得することはできましたが、ウォッチがサービス変数で動作していないため、テーブルからアイテムをクリックしても更新できません。このためのヒントはありますか?

前もって感謝します

4

1 に答える 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();
}

デモ:フィドル

于 2013-03-01T13:56:45.417 に答える