How pass data to $mdDialog in angular material

2019-01-27 23:58发布

问题:

I want to pass some data to $mdDialog. In fact i have tow controller in separate file. here is my controller code

function openDialog(id) {
        $mdDialog.show({
            locals:{
                profileId: id
            },
            controller: ['$scope', 'profileId', function($scope, profileId) {
              var self = this;
                self.profileId= profileId;
            }],
            controllerAs: 'profileCtrl',
            templateUrl: 'view/profile.html',
            parent: angular.element(document.body),
            clickOutsideToClose:true

        })
    }

I want tp pass profileId to profileController and display profile data. In profile controller i get data as this

function profileController($scope,..., profileId){

}

but this error apear in console

  Error: [$injector:unpr] Unknown provider: profileIdProvider <- profileId<- ProfileController

what is this error and how to fix it?

回答1:

I added ng-controller="ProfileController as profileController" in profile template and this was due to an error. By removing it my problem solved.



回答2:

I think you must do this:

controller: ['$scope', function($scope) {
              var self = this;
                self.profileId= $scope.profileId;
            }]

Your profileId Is in the scope.

You can use locals to pass data: Exemple from official website:

function showDialog($event) {
       var parentEl = angular.element(document.body);
       $mdDialog.show({
         parent: parentEl,
         targetEvent: $event,
         template:
           '<md-dialog aria-label="List dialog">' +
           '  <md-dialog-content>'+
           '    <md-list>'+
           '      <md-list-item ng-repeat="item in items">'+
           '       <p>Number {{item}}</p>' +
           '      '+
           '    </md-list-item></md-list>'+
           '  </md-dialog-content>' +
           '  <md-dialog-actions>' +
           '    <md-button ng-click="closeDialog()" class="md-primary">' +
           '      Close Dialog' +
           '    </md-button>' +
           '  </md-dialog-actions>' +
           '</md-dialog>',
         locals: {
           items: $scope.items
         },
         controller: DialogController
      });

Where items is a data passed to the dialog



回答3:

Take the fast route!

openDialog = (items) => 
    $mdDialog.show({
        templateUrl: 'view/profile.html',
        controller: $scope => $scope.items = items
    })

$scope.items can now be used in the dialog template ☺