Select Value not Init in AngularJs and JQueryMobile

╄→尐↘猪︶ㄣ 提交于 2019-12-24 21:17:17

问题


i have a html code like that

<select id="selectCatagoryFood" data-role="listview" data-native-menu="true"
                ng-options="foodCatagory as foodCatagory.Description for foodCatagory in foodCatagories"
                ng-init=""
                ng-model="foodCatagory"
                ng-change="changeFoodCatagory(foodCatagory)">
                </select>

for getting data from AngularJs and JayData but after getting data select dropdown not selected value by default it show empty. what should i write in ng-init attribute


回答1:


You can either preset ng-model="foodCatagory" in the controller, for example:

$scope.foodCatagory = $scope.foodCatagories[0];

Or use ng-init like this:

ng-init="foodCatagory = foodCatagories[0]"

Note that if you load your foodCatagories asynchronously the data will most likely not be available when the directive compiles, which means ng-init will not work.

Since jQuery Mobile uses additional DOM elements to show and handle the select, you will need to tell it to refresh itself when the data has loaded and you have set the selected value.

You can for example write a directive to handle it:

app.directive('selectMenuRefresh', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var unbindWatcher = scope.$watch(attrs.ngModel, function(newValue, oldValue) {
        if (newValue && oldValue === undefined) {
          element.selectmenu('refresh');
          unbindWatcher();
        }
      });
    }
  };
});

And put it on the select element:

<select id="selectCatagoryFood" select-menu-refresh data-role="listview" data-native-menu="true" ng-options="foodCatagory as foodCatagory.Description for foodCatagory in foodCatagories" ng-model="foodCatagory" ng-change="changeFoodCatagory(foodCatagory)"></select>

This directive uses a $watch to detect when the ngModel changes. If there is a newValue (which there will be when $scope.foodCatagory = $scope.foodCatagories[0]; is performed) and the oldValue is undefined (which it will be the first time when the first select option is empty), it will call refresh on the select element. It will also unbind the $watch. Modify after your needs.

Example: http://plnkr.co/edit/GLelHd?p=preview

Note: Make sure that jQuery and jQuery Mobile is loaded before AngularJS.



来源:https://stackoverflow.com/questions/19609551/select-value-not-init-in-angularjs-and-jquerymobile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!