javascriptangularjsangularjs-controllerasangularjs-material

AngularJS Material mdDialog and display locals in a template


Part of the controller which spawn mdDialog looks like

$scope.removeAttendee = function(item) {

    console.log(item);

    $mdDialog.show({
        controller: DialogController,
        templateUrl: 'views/removeMsg.tmpl.html',
        parent: angular.element(document.body),
        clickOutsideToClose:true,
        controllerAs: 'ctrl',
        fullscreen: $scope.customFullscreen, // Only for -xs, -sm breakpoints.
        locals: {item: item}
    })

and controller for mdDialog:

function DialogController($scope, $mdDialog) {

    var attendee = this;

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

    $scope.cancel = function() {
        $mdDialog.cancel();
    };

    $scope.save = function(response) {
        $mdDialog.hide(response);
    };

    $scope.remove = function(response) {
        $mdDialog.hide(response);
    };

}

removeMsg.tmpl.html has that code

<p>You are going to remove {{ ctrl.item.firstName }} {{ ctrl.item.lastName }} from the lunch list.</p>

But I'm not able to display related values even when I will change code to something simple like

locals { item: "test" }

and related part to

{{ ctrl.item }}

Any suggestions why I'm not getting display those values?


Solution

  • Since you're using DialogController with controllerAs alias, you should assign resolved value to controller context item variable

    function DialogController($scope,$mdDialog,item){//Item value will resolve via locals
        var attendee = this;
        attendee.item = item; // this line is important.
    
        $scope.hide = function() {
            $mdDialog.hide();
        };
    
        $scope.cancel = function() {
            $mdDialog.cancel();
        };
    
        $scope.save = function(response) {
            $mdDialog.hide(response);
        };
    
        $scope.remove = function(response) {
            $mdDialog.hide(response);
        };
    }
    

    Apart from this, please shift $scope methods to use attendee(this). As controllerAs pattern doesn't encourage to use $scope in controller.