Jonathan Anctil
Jonathan Anctil

Reputation: 1037

How to add buttons dynamically in Kendo UI toolbar?

I have a problem with the Kendo UI toolbar. Actually, every buttons are loaded during the toolbar initialization.

But some requirements ask to add buttons dynamically.

Here is a sample of how we load the buttons in a page controller:

...
$scope.toolbarButtons = [{
    type: 'button',
    text: 'Button 1',     
    click: 'clickButton1'
}, {
    type: 'toggleButton',
    text: 'Button 2'
}, {
    type: 'button',
    text: 'Button 3'
}
...

And how we add the toolbar and pass the buttons to the directive :

<toolbar buttons="toolbarButtons"></toolbar>

return {
    scope: false,
    restrict: 'E',
    template: '<div kendo-toolbar="toolbar"></div>',
    controller: 'ToolbarController',
    link: function ($scope, element, attr) {

        $scope.buttons = $scope[attr.buttons];

        // Code to manage the toolbar
        ...
    };

I tried to change the scope binding of the buttons array:

scope: {
    buttons: '='
}

But when I add a button in the toolbarButtons array, the button is not displayed.

Upvotes: 3

Views: 3928

Answers (1)

OnaBai
OnaBai

Reputation: 40887

There is an add method in Kendo UI toolbar for adding a button. You should do:

var toolbar = $("#toolbar").data("kendoToolBar");
toolbar.add ({ type: "button", text: "Button N", id: "buttonN" });

Example:

$(document).ready(function() {
  $("#toolbar").kendoToolBar({
    items: [
      {
        type: 'button',
        text: 'Button 1'
      },
      {
        type: 'button',
        text: 'Button 2'
      },
      {
        type: 'button',
        text: 'Button 3'
      }
    ]
  });

  var n = 4;
  $("#add").on("click", function() {
    var toolbar = $("#toolbar").data("kendoToolBar");
    toolbar.add ({ type: "button", text: "Button " + n, id: "button" + n });
    n++;
  });
});
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2015.2.624/styles/kendo.common.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2015.2.624/styles/kendo.default.css" />

<script src="https://kendo.cdn.telerik.com/2015.2.624/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2015.2.624/js/kendo.all.min.js"></script>

<button class="k-button" id="add">Add Button</button>
<div id="toolbar"></div>

Upvotes: 3

Related Questions