1

I have tried a basic angularjs app. My controller is working ok but template in directive doesn't seems to work, please suggest the solution.

Below is my code

index.html

   <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="DataApp1">
    <head>

        <script src="Scripts/angular.min.js"></script>
    </head>
    <body>

        <div data-ng-controller="DataController1">     
            <data-directive> </data-directive>
         </div>

        <script src="Scripts/App.js"></script>
    </body>
    </html>

app.js

 /// <reference path="angular.js" />

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

myapp.controller("DataController1", function ($scope) {

});

myapp.directive("dataDirective", function () {
    return {
        restrict: 'E',
        template: '<h2>Hi</h2>'
    };
});

2 Answers 2

3

The problem is on your naming convention, Any text accompanied by data- is considered without it in angularjs,

Example: data-ng-model, data-ng-bind

Name your directive like this directive and call it with or without using data-, both are same

Then it works!

Working Plunker with your code

See docs

Directive Docs

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

1 Comment

ok great, I knew it but made mistake :) thanks for the answer :)
0

I would refrain from using data- on your angular directives. It's really not needed.

Also, i would place the ng-app directive on your body tag, it increases the speed of your page load. Even if it is only slightly, every little bit counts when you get into enterprise level application development.

2 Comments

data- is optional , but is it really speedup my page load if I put ng-app directive to my body tag? how much faster? can you prove it by any example?
It's slightly faster as it reduces the size of your scope by not having to include the elements in the <head>. The only reason why you would want to declare ng-app on the html document is if you wanted to manipulate the title with it but then you can do the same thing by using $window.

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.