uttam uttam - 1 month ago 17
AngularJS Question

Angular is not working on the routed HTML page

One of my HTML pages is like this:

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script>
var module = angular.module("sampleApp", ['ngRoute']);

module.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/route1', {
templateUrl: "test.html"
}).
otherwise({
redirectTo: '/'
});
}]);
</script>
</head>
<body ng-app="sampleApp">
<a href="#/route1" role="button">Route</a>
<div ng-app="myApp" ng-view></div>
</body>
</html>


I'm trying to navigate from this page to test.html through angular routing. test.html is as follows



<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.my = 10;
ab = function() {
alert($scope.my);
}
});
</script>
<meta charset="UTF-8">
<div ng-app="myApp" data-ng-controller="myCtrl">
{{10+20}}
{{my}}
<button onclick="ab()">click</button>
</div>


But angular is not working in test.html, i.e., {{10+20}} and {{my}} is displayed as it is. when I run test.html separately, then angular is working well. But when routed from the first html page it is not working.

Please help me out. Thanks.

Answer

<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
        <script>
            var module = angular.module("sampleApp", ['ngRoute']);

            module.config(['$routeProvider',
            function($routeProvider) {
                $routeProvider.
                    when('/route1', {
                        controller: 'myCtrl',
                        templateUrl: 'test.html'
                    }).
                    otherwise({
                        redirectTo: '/'
                    });
            }]);
          
          module.controller("MainController", function($scope) {
        
    });
          
    module.controller("myCtrl", function($scope) {
        $scope.my = 10;
        ab = function() {
            alert($scope.my);
        }
    });
        </script>
    </head>
    <body ng-app="sampleApp">
      <div ng-controller="MainController"> 
           <a href="#/route1" role="button">Route</a> 
            <ng-view>

            </ng-view> 
        </div> 
    </body>
</html>

And in your test.html, put this only :

<div>
    {{10+20}}
        {{my}}
        <button onclick="ab()">click</button>
</div>

This all are in a working condition, i have test it in my local. You have to just make test.html file then all code snippet will works fine

Comments