Dan Dan - 4 months ago 11
AngularJS Question

How to pass scope from directive to template

I can't understand how to pass my scope object from directive to template, i need to change background my div, i did like this:

var app = angular.module('comments', []);
app.controller('fooCtrl', function($scope){
$scope.bg= {};
})

app.directive('foo', function ($rootScope) {
return {
link: function (scope, element, attrs) {
element.bind('click', function(){
scope.bg= {background: 'blue'};
});
}
};
});


and:

<div ng-app="comments">
<div ng-controller="fooCtrl">
<foo>foo</foo>
<foo>foo</foo>
<foo>foo</foo>
<foo>foo</foo>
<div id="form" ng-style="bg"></div>
</div>
</div>


But this is not working.

It's probably so funny question, and my code is awful, but it my first Angular app. Hope for your help.

Answer

you can use controller attribute in the directive to pass the current controller scope to directive, then change the value of the controller and use $timeout to update the value back to original controller. please check the sample

angular.module('testApp', [])
            .directive('foo', function($timeout) {
                return {
                    restrict: "E",
                    scope: {
                        controller: '=',
                        color: '@'
                    },
                    link: function(scope, element, attrs) {
                        element.bind('click', function() {
                            $timeout(function() {
                              scope.controller.bg = {
                                   background: scope.color
                               };
                            });
                        });
                    }
                };
            })
            .controller('AppCtrl', function () {});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="testApp">
    <div ng-controller="AppCtrl as vm">
      <foo controller="vm" color="red">foo</foo>
      <foo controller="vm" color="black">foo</foo>
      <foo controller="vm" color="blue">foo</foo>
      <foo controller="vm" color="yellow">foo</foo>


        <div id="form" ng-style="vm.bg">
            {{vm.bg.background}}
        </div>
    </div>
</body>