JSFiddle - React, Tailwind, and code Playground

by Yoichiro Tanaka

HTML

<div ng-app="myapp">
    <div ng-controller="mycontroller1">
        <mydirective text="foo" on-load="onLoad(api)"></mydirective>
        <button ng-click="onClick()">Set text</button>
    </div>
    <div ng-controller="mycontroller2">
        <mydirective text="bar" on-load="onLoad(api)"></mydirective>
        <button ng-click="onClick()">Set text</button>
    </div>
</div>

JavaScript

var myapp = angular.module("myapp", []);

myapp.controller("mycontroller1", ["$scope", function($scope) {
    $scope.onClick = function() {
        $scope.api.setText("Yoichiro");
    };
    $scope.onLoad = function(api) {
        $scope.api = api;
    };
}]);

myapp.controller("mycontroller2", ["$scope", function($scope) {
    $scope.onClick = function() {
        $scope.api.setText("Tanaka");
    };
    $scope.onLoad = function(api) {
        $scope.api = api;
    };
}]);

myapp.directive("mydirective", [function() {
    return {
        restrict: "E",
        template: "<span></span>",
        scope: {
            onLoad: "&",
            text: "@"
        },
        compile: function(element, attrs) {
            return function(scope, element, attrs, ctrl) {
                element.text(scope.text);
                if (scope.onLoad) {
                    scope.onLoad({
                        api: (function(scope, element) {
                            return {
                                setText: function(text) {
                                    element.text(text);
                                }
                            };
                        })(scope, element)
                    });
                }
            };
        }
    };
}]);