/java-script/

AngularJS – Directive Communication

2014-07-29 21:12:54

Option 1 - One way...

example

In this example we have one controller and directive. Directive use controller api ($scope.ctrl.api) to change controller's model.

angular.module('App', [])

    .controller('bondingCtrl', function ($scope) {

        $scope.model = 'lorem';

        $scope.ctrl = {
            api: {
                set: function (newModel) {
                    $scope.model = newModel;
                },
                get: function () {
                    return $scope.model;
                }
            }
        }
    })

    .directive('simple', function () {
        return {
            restrict: 'E',
            scope: {
                'name': '@',
                'api': '='
            },
            template: '<button ng-click='"someMethod()"'>{{name}}</button>',
            controller: function ($scope) {
                $scope.someMethod = function () {
                    $scope.api.set($scope.name);
                };
            }
        }
    })
;
<!DOCTYPE html>

<html>
<head lang='"en"'>
<meta charset="utf-8"/>
<title>AngularJS-Directive-Communication</title>
</head>
<body>
<section ng-app='"App"' ng-controller='"bondingCtrl"'>
<h1>Current model: {{model}}</h1>
<simple api='"ctrl.api"' name='"A"'></simple>
<simple api='"ctrl.api"' name='"B"'></simple>
</section>
<script src='"../bower_components/angularjs/angular.min.js"'></script>
<script src='"../bower_components/jquery/dist/jquery.min.js"'></script>
<script src='"app.js"'></script>
</body>
</html>

Option 2 - Second way...

example

In this example we don't have controller api, instead of it we set controller model to directive.

angular.module('App', [])

    .controller('bondingCtrl', function ($scope) {
        $scope.model = 'lorem';
        $scope.someMethod = function () {
            $scope.model = 'lorem';
        };
    })

    .directive('simple', function () {
        return {
            restrict: 'E',
            scope: {
                'name': '@',
                'model': '='
            },
            template: '  
<button ng-click='"someMethod()"'> from directive: {{name}}</button>{{model}}',
            controller: function ($scope) {
                $scope.someMethod = function () {
                    $scope.model = $scope.name;
                };
            }
        }
    })
;
<!DOCTYPE html>

<html>
<head lang='"en"'>
<meta charset="utf-8"/>
<title>AngularJS-Directive-Communication</title>
</head>
<body>
<section ng-app='"App"' ng-controller='"bondingCtrl"'>
<h1>Current model: {{model}}</h1>
<button ng-click='"someMethod()"'>from controller</button>
<simple model='"model"' name='"A"'></simple>
<simple model='"model"' name='"B"'></simple>
</section>
<script src='"../bower_components/angularjs/angular.min.js"'></script>
<script src='"../bower_components/jquery/dist/jquery.min.js"'></script>
<script src='"app.js"'></script>
</body>
</html>