Gabriel
Gabriel

Reputation: 439

How to correctly pass data to a modal box defined outside the scope

What I want to accomplish, is to be able to feed the modal box with data data so it can correctly display it. You can see here the jsfiddle where the simple test is located.

http://jsfiddle.net/GabrielBarcia/sjtog46f/1/

In my current learning project, I am using Bootstrap tabs and modal boxes, that is why I have the modal defined on the beginning of the code. On the real project, if I define the modal inside the tabs it is not correctly displayed, therefore I needed to ¨declare¨ it before the tabs start for it to work.

I was hoping that because triggering the modal from inside the controller, the directive on the modal had access to the data, but it seems like I was wrong. I have tried several ways but could not make it work, this is why I am asking for help. I need the directive to be able to show data on the modal as it does on the test of the directive inside the controller. Hope you guys can help

Here is working as I was expecting

<div ng-controller="dataInputCtrl">
    <div>
        <p>value A :
            <input type="textbox" ng-model="userData.a"></input>
        </p>
        <p>value B :
            <input type="textbox" ng-model="userData.b"></input>
        </p>
    </div>
    <div>
        <render-item directivedata="userData"></render-item> //Here is ok!
    </div>

Here is not

<div class="modal-body">
    <render-item directivedata="userData"></render-item> //here not ok
</div>

Upvotes: 1

Views: 221

Answers (1)

charlietfl
charlietfl

Reputation: 171669

Simple workaround would be bind the data to both controller and modal directive through a service

angular.module('app', [])
    .controller('dataInputCtrl', function ($scope, DataServ) {
    // data bound to service
    $scope.userData = DataServ.data;

}).factory('DataServ', function () {
    return {
        data: {}
    };

}).directive('renderItem', function (DataServ) {
    return {
        restrict: 'E',
        template: "<p> A = {{data.a}}</br>B = {{data.b}}</p>",
        link: function (scope, elem, attrs) {
            // data bound to service rather than passed from attribute
            scope.data = DataServ.data
        }
    };
});

You will still find using angular-ui-bootstrap a lot less problematic in the long run. It is heavily used and actively developed

DEMO

Upvotes: 1

Related Questions