How can I fill select2 data dynamically using angularjs

My case is that I want to use the createSearchChoice feature of the Select2 widget. So I found out I need to use an html input element instead of a select element and so I cannot use ng-repeat to populate the select2 widget. I find out there is a 'data' option and have been able to populate the select2 widget with static data, but not when I've tried to fill it dynamically.

What works:

html: <input class='select2' ui-select2='sel2props' type='hidden'>

in the controller:

$scope.sel2props = {
    createSearchChoice: ...

  data: [ 
    { id: 0, text: 'yabba' }
    etc
  ]
};

But if I try to set data to a variable which I can then set to whatever the database feeds me the widget isn't populated.

data: $scope.data;

function to retrieve data {
    $scope.data = retrieved data;
}

the retrieved data is exactly in the way specified.

If i set up a button to append the data key it will work:

$scope.appenddata = function () {
  $scope.data.push({id:1, text: 'anot'});
};

So I'm thinking it's a timing issue and I try $digest and $apply but they don't work in controllers. I tried to set up a directive and actually can do simple widgets, but not select2, so I was hoping not to go down that path, well that is to say I went down that path and drowned. If anyone could help out that would be great.

The solution is straight forward. Just push the elements onto the select2 data array rather than referencing another array.

function (result) {
  $scope.lookupOptions.data.length = 0; // remove old items
  angular.extend($scope.lookupOptions.data, result.data); // add new items                  
}

A trick I've recently made use of is to use Select2's query option to pass in your latest data on demand.

I've put together an example, wrapped in a custom directive. See this Plunk.