将Material Design Dialog中的对象放入主控制器

时间:2016-02-04 19:30:33

标签: javascript angularjs material-design

我有一个应用程序,允许用户在模态角度材质设计对话框中创建和编辑记录($ mdDialog) 我的问题是将对话框返回的对象放入主控制器中的集合中。有没有办法做到这一点?

angular.module("module").controller("mainController", function ($scope, $mdDialog) {
    $scope.Users = [];

    function OpenEditWindow(userToEdit) {
        $mdDialog.show({
            templateUrl: 'Views/user.html',
            controller: 'UserDialogController',
            clickOutsideToClose: true,
            locals: { // Envia valores para o controller do dialog
                User: userToEdit
            }
        }).then(function (data) {
            // Put the object edited into the collection on main controller, to show on the screen
            $scope.Users.push(data); // ******** NOT WORKS
        });
    }
});

angular.module('module')
.controller('UserDialogController', function ($scope, $mdDialog, User) {
    $scope.User = User;

    $scope.Save = function () {
        $mdDialog.hide($scope.User);
    }
});

2 个答案:

答案 0 :(得分:0)

$mdDialog.show返回的是一个承诺。您将then放在错误的位置。这在角材料文档here

中显示
angular.module("module").controller("mainController", function ($scope, $mdDialog) {
    $scope.Users = [];

    function OpenEditWindow(userToEdit) {
        var promise = $mdDialog.show({
            templateUrl: 'Views/user.html',
            controller: 'UserDialogController',
            clickOutsideToClose: true,
            locals: { // Envia valores para o controller do dialog
                User: userToEdit
            }
        });

        promise.then(function (data) {
            // Put the object edited into the collection on main controller, to show on the screen
            $scope.Users.push(data); // ******** NOT WORKS
        });
    }
});

答案 1 :(得分:0)

也许您可以集中数据并创建一个服务模型,以便在整个应用程序中保持用户的状态。这样的服务可以像其他依赖项一样传递到您的控制器中。

angular.module('module')
.controller('UserDialogController', function ($scope, $mdDialog, User, UserModel) {
    $scope.User = User;

    $scope.Save = function () {
        $mdDialog.hide($scope.User);
    }
});


angular.module('module').factory('UserModel', function () {

    var userModel = this;

    userModel.set = function(){
     ...
    }

    return userModel;
});

鉴于服务是单身,您可以保证每次都能访问最新和最好的信息。

尝试使用样式指南,这将极大地改善您的代码,逻辑和整体质量。这样的指南可能是John Papa's Angular Style Guide