$ scope is not available for ng template

I am trying to use modal to edit a form, the modal is in the ng-template script, but the form data is not showing when the edit button is clicked.
The $ constraint is not available to the script template.
I created Plunker here

$scope.setCurrentItem = function (item) {
    $scope.currentItem = item;
};

$scope.edit = function (item) {            //editing item
    $scope.setCurrentItem(angular.copy(item));            
    //$scope.editItem = item;
    openEditModal();
};

<!--html-->
<script type="text/ng-template" id="myModalContent.html">     
<label for="name">Role: </label>                                
<input type="text" ng-model="currentItem.roleName" required />
</script>

      

How can I fix this?

+3


source to share


1 answer


By default ui bootstrap $modal

uses $rootScope

as its default scope. But you are assuming it will automatically take over the scope of the controller that opened the dialog, which it doesn't. But there is a property scope

you can set to pass a region to the ui modal so that it uses that region and creates a child region from the provided region and will be used as the main region for the modal. This way your modal wrapper also takes a scope property in the settings and passes it on.

From doc

scope - the scope instance to be used for modal content (in fact, modal $ will create a child scope of the provided scope). The default is $ rootScope.

Examples of changes: -

  function openEditModal() {
     var modalOptions = {
        closeButtonText: 'Cancel',
        actionButtonText: 'Save role',
        headerText: 'Edit role',
        bodyText: '',
        scope:$scope //<-- Pass scope
    };

    Modal.showModal({ templateUrl: 'myModalContent.html', size: 'lg' }, modalOptions).then(function (result) {
        console.log("save!", result);
    });
  }

      



and in your service: -

  /*I just did this here based on my limited understanding of your code*/
  return $modal.open(angular.extend(tempModalDefaults, customModalOptions)).result;

      

From your modal template, pass the element back, I'm not sure if your template is generic, if so, you might want to consider using a different approach to pass the data back: -

  <button class="btn btn-primary" ng-click="modalOptions.ok(currentItem)">{{modalOptions.actionButtonText}}</button>

      

Demo

+5


source







All Articles