bhanu.cs
bhanu.cs

Reputation: 1365

Creating Custom directive do not work

I am trying to create a custom directive..

 <head>
    <script type="text/javascript" src="../Scripts/angular.min.js"></script>
    <script type="text/javascript" src="../Scripts/DataDirectives.js"></script>
    </head>
    <body  style="overflow: hidden" >
      <div ng-app="myApp">
        <SampleData></SampleData>
      </div>
    </body>

In a separate Javascript File called DataDirectives.js the followung code is present..

var app = angular.module('myApp', []);

app.directive('SampleData', function () {
    return {
        restrict: 'E',
        template: '<div>Sample Div,To test angular Directives</div>'
    };
});

So when I run the page,I cannot see any text on that page of that of the div element.What could be wrong with my above code. Thanks for the help in Advance... :)

Upvotes: 0

Views: 50

Answers (3)

Endre Simo
Endre Simo

Reputation: 11541

You are defining the angular directive in your template using camelcase naming convention. The angular directive should be declared in template like sample-data. Then in javascript file you can reference it like sampleData.

Taking these into consideration, you should change the code in the following manner:

<div ng-app="myApp">
   <sample-data></sample-data>
</div>

Another alternative would be to declare the directive inside an existing element. For example:

<div sample-data="exp"></dir>

And in javascript:

var app = angular.module('myApp', []);

app.directive('sampleData', function () {
    return {
        restrict: 'E',
        template: '<div>Sample Div,To test angular Directives</div>'
    };
});

Please see the lower cased version of sampleData.

Upvotes: 0

user3227295
user3227295

Reputation: 2156

in html write directive name: sample-data

in js sampleData

var app = angular.module('myApp', []);

app.directive('sampleData', function () {
    return {
        restrict: 'E',
        template: '<div>Sample Div,To test angular Directives</div>'
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp"  style="overflow: hidden" >
      <div ng-app="myApp">
        <sample-data></SampleData>
      </div>
    </body>

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You have 2 ng-app as well as you are not following the required naming convensions

var app = angular.module('myApp', []);

app.directive('sampleData', function() {
  return {
    restrict: 'E',
    template: '<div>Sample Div,To test angular Directives</div>'
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <sample-data></sample-data>
</div>

Upvotes: 2

Related Questions