2017-10-17 2 views
0

私の目玉プロジェクトでは、Angular.js materialを使用しています。そして私は$mdialogをカスタムコントローラーで表示したいと思っています。ここではユーザーがデータを変更し、このデータを変数$scopeに適用する必要があります。私は今何をすべきかの例:私は、ダイアログコントローラで次にAngular.js別のコントローラからの返信

function myControllerFn($scope, MyService){ 
    // I do copy of my service variable because I don't want to change it until user will click save button 
    $scope.name = angular.copy(MyService.name); 

    $scope.editCurrentProfile = function() { 
     $scope.showEditProfileDialog($scope.name).then(function(name){ 
        $scope.name = name; 
     } 
    } 

    $scope.showEditProfileDialog = function(name) { 
     var deferred = $q.defer(); 
     $mdDialog.show({ 
     controller: 'editProfileViewCtrl', 
     templateUrl: 'controllers/editProfileDialog.tmpl.html', 
     locals: { 
      name: name, 
      deferred: deferred 
     } 
     }); 
     return deferred.promise; 
    }; 
} 

function editProfileViewCtrl($scope, name, deffered) { 
    deferred.resolve('newName'); 
} 

しかし、私は、それは間違った方法だと思います。だから、新しいサービスなしで2つのView Controller間で通信する最善の方法は何ですか?または、より良いサービスを作成する:EditDialogService、ここで結果を保存しますか?

答えて

3

モーダルを開くと、show()関数は約束を返します。

$scope.showEditProfileDialog = function(name) { 
    var modalInstance = $mdDialog.show({ 
    controller: 'editProfileViewCtrl', 
    templateUrl: 'controllers/editProfileDialog.tmpl.html', 
    locals: { 
     name: name 
    } 
    }); 

    modalInstance.then(function(result){ 
     // acces what is returned 
     // In your case, you would do 
     $scope.name = result; 
    }, function(error){ 
     // Usually when you cancel your modal 
    }); 
} 

あなたのモーダルコントローラには$mdDialogを注入できます。

function editProfileViewCtrl($scope, name, $mdDialog) { 
    $scope.close = function() { 
     $mdDialog.hide('newName'); 
    } 
} 
+0

エラー(拒否約束)はどうですか? – Arti

+1

ああ、申し訳ありません。それを見つけた ! $ mdDialog.hide()で解決できる、または$ mdDialog.cancel()で拒否されたことの約束。ありがとう – Arti

-1

ユーザーをスコープ変数として使用してディレクティブを作成する必要があります。角はデータバインディングを処理しています。

-1

$ scopeにアクセスできる最小限のコントローラ機能を作成することは可能です。

$mdDialog.show({ 
    controller: function() { this.parent = $scope; }, 
    templateUrl: 'controllers/editProfileDialog.tmpl.html', 
    locals: { 
    name: name, 
    deferred: deferred 
    } 
}); 
関連する問題