简体   繁体   中英

AngularJs Modal set default value from rootScope

I have problem with angular modal value. I have $rootScope and on button im opening modal which contains , and I can't set default / selected value to that

<form>
    <input type="button" class="mobileUpdate" ng-click="openMobileUpdateModal()" />

    <script type="text/ng-template" id="mobileModal.html">
         <form name="modalForm">
             <div class="modal-body">
                   <p>Country</p>
                   <select id="countryMobile" ng-model="countryMobile" class="select-styled" name="countryMobile" required>
                       <option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
                   </select>
                </div>
             </div>
             <div class="modal-footer">
                 <input type="button" ng-click='confirm()' value="OK"/>
                <input type="button" ng-click='cancel()' value="Cancel"/>
             </div>
         </form>
     </script>

</form>


   $rootScope.openMobileUpdateModal = function () {

      $rootScope.countryMobile = $rootScope.country;
      var modalInstance = $modal.open({
        templateUrl: 'mobileModal.html',
        controller: ModalInstanceCtrl
      });
    };
    var ModalInstanceCtrl = function ($rootScope, $modalInstance) {
        $rootScope.confirm = function () {
         //do something
          $modalInstance.close();
        };
        $rootScope.cancel = function () {
          $modalInstance.dismiss();
        };
    };

Anyone know how to send value from $rootScope to modal, and set that value as default? Thanks

First of all there is syntax error you have double quote twise in you select tag code. Update it as below then try. And use $root in your ng-model.

<select id="countryMobile" ng-model="$root.countryMobile" class="select-styled" name="countryMobile" required>
      <option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
</select>

I'm not sure that I understand your problem correct but try do not use rootScope or modify and avoid rootScope modification.

If you need use some value from rootScope:

  1. extract this value to local scope of particular controller and after that use it
  2. Use WATCH operator to avoid situations when you render some value before it initialised.

<option ng-repeat> does not work in angularjs. you should use

<select id="countryMobile" ng-model="countryMobile" class="select-styled"   name="countryMobile" required ng-options="country.id as country.name for country in contries"></select>

http://docs.angularjs.org/api/ng/directive/select

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM