Brian
Brian

Reputation: 2305

Angularjs Directive Assistance with Bootstrap-UI $Dialog

I am working on creating a custom directive which creates a button within an ng-repeat and will bind to the current item. Once the button is clicked, a $dialog opens with a select2 box to select and change the user. On save the user replaces the current user within the ng-repeat. I have all of this working (though would appreciate any code review/revision help since this is my first directive), the part where I am stuck is how to now incorporate a call back to an angular service to push the updated user back to the database.

Here is my current plunker: http://plnkr.co/edit/nzR3mjeLK3kPynSIjE7t?p=preview

Is the best option here to call a function in the parent controller to call the service update?

Is there a way the directive itself should handle this?

Any help or direction would be greatly appreciated.

Upvotes: 0

Views: 248

Answers (1)

zs2020
zs2020

Reputation: 54514

You can inject a service module with the data persistence implemented inside the service in order to separate the logic from the directive.

.factory('service', function () {
    var service = {
      doSomething: function(result){
        //logic to do the data persistence
        console.log('saved!');
      }
    }

   return service;
})

.directive('delegateApproval', function($dialog, service) { //inject the 'service'

$scope.openDelegate = function(approval) {
    d.open().then(function(result) {

        $scope.approval._approver._user._lastName = '';
        $scope.approval._approver._user._firstName = result.empName;

        service.doSomething(approval); // consume the service
    });
};

Demo

Upvotes: 1

Related Questions