0

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> 

1 Answer 1

2

You are declaring directive in wrong way in html.

html name should be snake-case like this

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

JSFIDDLE

Sign up to request clarification or add additional context in comments.

3 Comments

do i need to change directive name also ?
nope directive name should be camel case. check my fiddle that i added in the answer @BHARATATHOTA
In your example it adds a button element inside <my-button> tag.How can i implement <my-button> tag is completely replaced by template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.