Binding value in md-dialog to ng-model in directive

时间:2016-03-04 18:13:14

标签: javascript angularjs material-design angular-material

I looked through a lot of question before coming here, but couldn't find any one that solved my problem. So here I am.

I created this directive:

.directive('myDirective', {'$mdDialog',
    function($mdDialog){
    return {
        restrict: 'E',
        templateUrl: TEMPLATE_URL,
        scope: {
            type: '@',
            fieldName: '@',
            ngModel: '='
        },
        link: function($scope, $element, $attrs){
            $scope.close = function(){
                $mdDialog.cancel();
            }

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

            $scope.showDialog= function(){
                var options = {
                    templateUrl: MODAL_TEMPLATE_URL,
                    scope: $scope,
                    controller: 'MyController'
                };

                $mdDialog.show(options);
            };
        }
    };
}]);

The directive opens a dialog (using Angular Material) and everything renders correctly in it, but there's an ng-click that calls the "selectItem" function and passes in an object (item) doesn't persist on the ngModel text field. The object has the "Name" property set. It appears for a second inside the text field and vanishes. And then, if I try to open the dialog again, the ng-click doesn't trigger the "showDialog" function anymore.

Here's the directive template:

<md-input-container class="field-result">
    <label>{{fieldName}}</label>
    <input type="text" ng-model="ngModel.Name" ng-disabled="true">
</md-input-container>
<md-button class="md-icon-button md-raised icon icon-button icon-search" ng-click="showDialog()"></md-button>

So here's what I want: to show the value of the property "Name" on the text field with ngModel, once it's set, and fix the ng-click problem with the "showDialog" button.

Thanks in advance!

1 个答案:

答案 0 :(得分:3)

由于scope: $scope,

,指令范围由$ mdDialog更改

您需要将preserveScope: true,添加到对话框选项中。见plunker