Search code examples
angularjsdevextreme

How to refresh data source on DevExtreme menu


I'm using angular-translate for i18n. Somewhat unfortunately, $translate service asynchronously loads strings.

I've copied in the relevant controller code. What is the best way to replace the current datasource items with a new array of items after the translations are loaded? (or after the user signs in this case). The code seems a bit clunky.

See below for my attempt.

var items = [
  {
    text: 'This option remains',
    uiState: 'signin',
    icon: 'user'
  }];

$scope.accountMenuDS = new DevExpress.data.DataSource({
  store: {
    type: "array",
    key: "text",
    data: items
  }
});

$translate(['users.signin']).then(function (trans) {
  if (!user) {

    var newItems = [
      {
        text: 'hello',
        uiState: 'signin',
        icon: 'key'
      }
    ];

    Array.prototype.splice.apply(items, [0, newItems.length].concat(newItems)); // is there a better way than this?

    $scope.accountMenuDS.reload();

  } else {
    // handle signed in case later
  }
});

Solution

  • In your case you can use the bindingOptions field to provide two-way binding:

    <div ng-controller="myCtrl">
        <div dx-menu="menuOptions"></div>
        <div dx-button="buttonOptions"></div>
    </div>
    

    Controller code:

    myApp.controller("myCtrl", function($scope) {
        $scope.menuData = [/*...*/];
    
        $scope.menuOptions = {
            bindingOptions: {
                dataSource: "menuData"
            }
        };
    
        $scope.buttonOptions = {
            text: "Update data",
            onClick: function() {
                $scope.menuData.push({
                    text: "Item 3"
                });
            }
        };
    });
    

    See this plunker demo as well.