简体   繁体   中英

AngularJs directives: Copied code verbatim from official tutorial and it doesn't work. Why?

The official tutorial is from here: https://docs.angularjs.org/guide/directive

I copied the official code from "Creating Directives", sub-header "Template-expanding directive". Example 1 works perfectly (the example where there are only script.js and index.html ), with my browser rendering the desired results. Example 2 is a simple expansion of Example 1, replacing the "template" line from the directive file with a "templateUrl" line, and adding a my-customer.html file as the template. However, this doesn't work for me.

The copied code are as follows. All files are put in the same folder:

  1. index3.html:

     <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example12-production</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"> </script> <script src="script3.js"></script> </head> <body ng-app="docsTemplateUrlDirective"> <div ng-controller="Controller"> <div my-customer></div> </div> </body> </html> 
  2. script3.js:

     angular.module('docsTemplateUrlDirective', []) .controller('Controller', ['$scope', function($scope) { $scope.customer = { name: 'Naomi', address: '1600 Amphitheatre' }; }]) .directive('myCustomer', function() { return { templateUrl: 'my-customer.html' }; }); 
  3. my-customer.html:

Name: {{customer.name}} Address: {{customer.address}}

Why do I get a blank page when I open index3.html in my browser?

Fixed it by disabling cache when developer tool is on (option chosen in the js console preferences of Chrome). The code was correct. It wasn't rendered correctly because of cache.

index.html

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

<body ng-app="docsTemplateUrlDirective">
    <div ng-controller="Controller">
        <div my-customer></div>
    </div>
</body>

my-customer.html

Name: {{customer.name}} Address: {{customer.address}}

script.js

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

app.controller('Controller', ['$scope', function($scope) {
    $scope.customer = {
        name: 'Naomi',
        address: '1600 Amphitheatre'
    };
}]);

app.directive('myCustomer', function() {
    return {
        templateUrl: 'my-customer.html'
    };
});

above code fine work in my pc....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM