Lexi
Lexi

Reputation: 324

Use in-file Javascript with AngularJS and Apache Tiles

I have been learning AngularJs and currently have an application that uses Apache Tiles. Prior to adding AngularJs to the application, I had a working piece of code inside my footer tile that calculated the current year that looks like this:

footer.html

    <script type="text/javascript">
          var year = new Date().getFullYear();
    </script>

    <tr ng-Controller="AppController">
       <td>Created <script>document.write(year)</script>
       </td>
    </tr>

controller.js

    var controllers = {};
    controllers.AppController = ['$scope', function ($scope) {
    $scope.currentYear = new Date().getFullYear();
    }];
    proxy.controller(controllers);

app.js

     var proxy = angular.module('proxy',['ngRoute'])
           .config(function($routeProvider) {
            $routeProvider.when('/index',{
                 templateUrl: 'search.jsp',
                 controller: 'AppController'
            });
     });

The footer now only shows "Created" on the index.html page. Is there a way with angular that I can successfully calculate the year? Why does the JS in this file stop working when AngularJs is added to the application?

Upvotes: 2

Views: 466

Answers (1)

Ravvy
Ravvy

Reputation: 199

Since you're using AngularJS, you can write the code like this:

<script type="text/javascript">
        angular.module('app', []).controller('YearController', ['$scope', function ($scope) {

            $scope.currentYear = new Date().getFullYear();

        }]);
</script>

<table ng-app="app">
    <tr ng-controller="YearController">
        <td>
            Created {{currentYear}}
        </td>
    </tr>
</table>

Edit: This is how it would look like if it was in it's own separate HTML and JavaScript files.

index.html:

<!DOCTYPE html >
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="app">  
    <div ng-include="'footer.html'"></div>
</body>
</html>

footer.html:

<table>
    <tr ng-controller="YearController">
        <td>
            Created {{currentYear}}
        </td>
    </tr>
</table>

app.js (better to have it's own separate file):

var app = angular.module('app', []);
var controllers = {};
controllers.YearController = ['$scope', function ($scope) {

    $scope.currentYear = new Date().getFullYear();

}];
app.controller(controllers);

Upvotes: 2

Related Questions