BHARAT ATHOTA
BHARAT ATHOTA

Reputation: 201

How to implement custom directive in angular js?

I tried to build a custom 'button' directive with the following code.But some where it went wrong could you please help me to sort it out.and here I am attaching code snippet to get a clear picture. Thanks in Advance.

<html>

<head>
    <title>Custom Directives</title>
</head>

<body>
<h2>AngularJS</h2>

<div ng-app = "mainApp" ng-controller = "ButtonController">
    <myButton name="Sai"></myButton><br/>
    <myButton name="Bharat"></myButton>
</div>

<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

<script>
    var mainApp = angular.module("mainApp", []);

    mainApp.directive('myButton', function() {
        var directive = {};
        directive.restrict = 'E';
        directive.transclude = true;
        directive.template = "<button>{{myButton.name}}</button>";


        directive.scope = {
            myButton : "=name"
        }

        directive.compile = function(element, attributes) {
            element.css("border", "1px solid #cccccc");

            var linkFunction = function($scope, element, attributes) {
                element.html("<button> $scope.myButton.name </button>");
            }
            return linkFunction;
        }

        return directive;
    });

    mainApp.controller('ButtonController', function($scope) {
        $scope.Sai = {};
        $scope.Sai.name = "Sai";

        $scope.Bharat = {};
        $scope.Bharat.name = "Bharat";

    });

</script>

</body>
</html> 

Upvotes: 0

Views: 38

Answers (1)

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

You are declaring directive in wrong way in html.

html name should be snake-case like this

<my-button name="Bharat"></my-button>

JSFIDDLE

Upvotes: 2

Related Questions