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