Pregunta

my AngularJS web app needs (as you may guess) to show modal popups sometime. Before learning AngularJS I used to centralize my code using Namespaces, and I tipically put all the UI stuff in a proper namespace, like: MyProj.UI.Dialogs.Modal.show() (just an example).

Now I', trying to apply the same logic in AngularJS. So, I created a directive:

app.directive('modal', function ($compile) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: '/partials/site/modal.html'
    }
});

with the following template:

<div>
    <h2>{{title}}</h2>
    <p>{{text}}</p>
</div>

so I can use the modal tag in my html.

Now, to control the modal behavior I'd like to use a service, something like:

angular.module('ui', [])
    .factory('ui', function ($rootScope) {
        var service = {
            showConfirm: function (title, text, callback) {
                $rootScope.showModal = true;
            }
        };

        return service;
    }
);

I'd use it from any controller:

app.controller('MyCntl', function (ui) {
    $scope.delete = function (referer) {
        ui.showConfirm("Confirm", "Please confirm action", function () {});
    }
});

But my question is: how do I pass values from the controller, to the service, to the directive?

¿Fue útil?

Solución

Here is a plunker: http://plnkr.co/edit/JLDDsTzSAHaitsZ4dxtL?p=preview

Bind the service to the directive's scope:

app.directive('modal', function (ui) {
    return {
        restrict: 'E',
        replace: true,
        scope:{},
        templateUrl: 'modal.html',
        link: function(scope){
          scope.ui = ui;
        }
    }
});

service:

angular.module('ui', [])
    .factory('ui', function ($rootScope) {

        var _callback = null;

        var service = {
            confirm: function(confirmed){
              if(confirmed) _callback();
              service.show = false;
              _callback = null;
            },
            showConfirm: function (title, text, callback) {
                service.show = true;
                service.title = title;
                service.text = text;
                _callback = callback;
            }
        };

        return service;
    }
);

Template:

<div ng-if="ui.show" class="modal">
    <h2>{{ui.title}}</h2>
    <p>{{ui.text}}</p>
    <button ng-click="ui.confirm(true)">ok</button>
    <button ng-click="ui.confirm(false)">cancel</button>
</div>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top