Solved

Angular.js site not responding to clicks

Posted on 2015-02-14
6
105 Views
Last Modified: 2016-11-08
I have page where I'm running the angular.js on-page

I noticed that the menu became unresponsive and then when I built the functionality none of the buttons react either

After looking at the code and doing a lot of trial and error I found out that it was the declaration of the module that caused this to happen

Any idea what can be wrong ?


<body ng-controller="UpdateUser" style="background:#000;"> - when I have the ng-controller set to UpdateUser anything I click on the page becomes unresponsive or doesn't do what it's supposed to do - i.e. menus etc just doesn't resond
0
Comment
Question by:DanteAdmin
  • 3
  • 2
6 Comments
 
LVL 53

Expert Comment

by:COBOLdinosaur
ID: 40610000
It is not likely that you are going to get much help when the only information you give us is one line of markup (the body tag).

Post a link to the page so we can do diagnostics and see what errors exist and whether there are conflicts with other components in the page.

Cd&
0
 

Author Comment

by:DanteAdmin
ID: 40610560
Thanks Cd& - I had to little info myself so shouldn't have posted anything really

I've figured out from some reading that it's the

$locationProvider.html5Mode(true);

That is causing this. Anything I click on is just being updated in the URL

<ul class="nav navbar-nav">
            <li><a href="viewQueue.php">View Queue</a></li>
            <li><a href="addBooking.php">New Customer</a></li>
          </ul>

Open in new window


Clicking on any of these two simply updates the URL path to "localhost:8080/viewQueue.php" and nothing else happens. When clicking a button with a ng-controller nothing happens

<script>
    angular.module('myApp', [], function($locationProvider) {
      $locationProvider.html5Mode(true);
    });
    
    function UpdateUser($scope, $location, $http) {
      $scope.userPhoneNo = $location.search()['userPhoneNo'];
      
      $http.get('/xxxx/rest/user/phone/' + $scope.userPhoneNo)
	      .success(function(data, status, headers, config) {
	      $scope.userDetails = data;
	      $scope.userName = $scope.userDetails.name;
	      $scope.userEmail = $scope.userDetails.email;
	      $scope.notes = $location.search()['customerNotes'];
	      $scope.userId = $location.search()['customerId'];
	  		})
	  
	  $postUpdateUser = function() {
		$http({
		    method: 'POST',
		    url: '/WhyQApp/rest/user/amend/',
		    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
		    transformRequest: function(obj) {
		        var str = [];
		        for(var p in obj)
		        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
		        return str.join("&");
		    },
		    data: {userId: $scope.userId, newUserName: $scope.userName, newUserEmail: $scope.userName, newUserPhoneNo: $scope.userPhoneNo}
		})
		
		.success(function (data) {
			$scope.successTextAlert = "Success - customer data updated!";
			$scope.showSuccessAlert = true;
		})
		
		.error(function() {
				$scope.successTextAlert = "Something went wrong - no updates";
				$scope.showSuccessAlert = true;
			})	
		}      
    }
</script>

Open in new window



Maybe I should just leave $location and look at routers? I only need to grab the URL value on two locations in the entire app so I was hoping this solution would work and could be resolved

Many thanks
0
 
LVL 30

Accepted Solution

by:
Alexandre Simões earned 500 total points
ID: 40610773
First thing, and as kind of a disclaimer, using AngularJS in a multi-page scenario is a bad practice.
If all you want is its dual-binding mechanism then you're better off with KnockoutJS or have a look at ReactJS.

Going through the path of routes has other implications that might not work for you if you're using them in a multi-page scenario.
This said, here's the solution without routing: http://plnkr.co/edit/H4hfzvqWHldtQjLxy7zO
It's a bit (too much for my taste) hacky. You need to enable html5Mode in the config and add a base link in the HTML (line 11 of the index.html).
So this is the solution without routing involved.

If it's not feasible for you to refactor your app into a single-page app of completely drop angular, this would probably be your best shot.

Code as a reference
HTML
<!DOCTYPE html>
<html ng-app="myapp">

  <head>
    <script data-require="angular.js@1.3.13" data-semver="1.3.13" src="https://code.angularjs.org/1.3.13/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="Main">
    <base href="/">
    <h1>Demo</h1>
    <h2 ng-bind="abc"></h2>
  </body>

</html>

Open in new window

JavaScript
angular.module('myapp', [])

  .config(function($locationProvider){
    $locationProvider.html5Mode(true);
  })
  
  .controller('Main', function($scope, $location){
    
    $scope.abc = $location.search().abc;
    
  });

Open in new window


Cheers mate
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:DanteAdmin
ID: 40616451
Thanks for your help, I've just tested in a few different ways but still when I click on anything on the site, the URL just updates, it doesn't actually take me to the <a href> link I'm clicking

The same for any "submit button" I click on - just doesn't react

Is it not possible to make have Angular.JS to read the URL and then just act as normal with links etc?

I'm aware we are not doing this the intended way but will be a lot of work for us to re-write just to read a http variable

Thanks again.

angular.module('myApp', [])

  .config(function($locationProvider){
    $locationProvider.html5Mode(true);
  })
  
  .controller('UpdateUser', function($scope, $location, $http){
    
    $scope.userPhoneNo = $location.search()['userPhoneNo'];
      $scope.abc = $location.search().abc;
      $http.get('/WhyQApp/rest/user/phone/' + $scope.userPhoneNo)
	      .success(function(data, status, headers, config) {
	      $scope.userDetails = data;
	      $scope.userName = $scope.userDetails.name;
	      $scope.userEmail = $scope.userDetails.email;
	      $scope.notes = $location.search()['customerNotes'];
	      $scope.userId = $location.search()['customerId'];
	  		})
	  
	  $postUpdateUser = function() {
		$http({
		    method: 'POST',
		    url: 'rest/user/amend/',
		    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
		    transformRequest: function(obj) {
		        var str = [];
		        for(var p in obj)
		        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
		        return str.join("&");
		    },
		    data: {userId: $scope.userId, newUserName: $scope.userName, newUserEmail: $scope.userName, newUserPhoneNo: $scope.userPhoneNo}
		})
		
		.success(function (data) {
			$scope.successTextAlert = "Success - customer data updated!";
			$scope.showSuccessAlert = true;
		})
		
		.error(function() {
				$scope.successTextAlert = "Something went wrong - no updates";
				$scope.showSuccessAlert = true;
			})	
		}
    
  });

Open in new window


<!DOCTYPE html>
<html lang="en" ng-app="myApp">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="favicon.ico">

    <title>System</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="navbar-fixed-top.css" rel="stylesheet">


    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script src="vendor/angular-1.2.15/angular.min.js"></script>
<script src="js/updateUser.js"></script>

  </head>

  <body ng-controller="UpdateUser" style="background:#000;">
	<base href="/">
	<h2 ng-bind="abc"></h2>
	
	<div class="alert alert-success" ng-show="showSuccessAlert" style="color:#fff;">
	   <button type="button" class="close" data-ng-click="switchBool('showSuccessAlert')" >×</button>
	   {{successTextAlert}}
	 </div>
	
    <!-- Fixed navbar -->
    <div class="navbar navbar-default navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#"><img src="img/u-whitebg-logo.png" style="height:50px; margin-top:-18px;" /></a>
        </div>
        <div class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li><a href="viewQueue.php">View Queue</a></li>
            <li><a href="addBooking.php">New Customer</a></li>
          </ul>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="xx"><img src="img/social/fb.png" style="height:40px; float:left; margin:-8px 0 0 0;" /></a></li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </div>

    <div style="width:100%; text-align:center; color:#fff;">
  	
    <h1 style="text-align:center;"><img src="img/clientlogo/logo.png" alt="Client Logo" style="padding:0 0 10px 0;"/></h1>
    <hr/>
    
    <form class="form-inline" role="form">
	  <div class="form-group">
	  	<span style="font-size:16px;">USER DETAILS</span>
	  	<div class="input-group">
	      <label class="sr-only" for="exampleInputEmail2">Name</label>
	      <input type="name" ng-model="userName" class="form-control">
	    </div>
	    <div class="input-group">
	      <label class="sr-only" for="exampleInputEmail2">Email</label>
	      <div class="input-group-addon">@</div>
	      <input type="email" class="form-control" ng-model="userEmail">
	    </div>
	  </div>
	  <div class="form-group">
	    <label class="sr-only" for="exampleInputPassword2">Mobile Phone</label>
	    <input type="telephone" class="form-control" ng-model="userPhoneNo">
	  </div>
	  <button type="submit" class="btn btn-info" ng-click='postUpdateUser()'>Update details</button>
	</form>
	<hr/>
	
    <form class="form-inline" role="form">
    <span style="font-size:16px;">NOTES</span>
	  <div class="form-group">
	    <label class="sr-only" for="exampleInputPassword2">Notes</label>
	    <input type="text" class="form-control" ng-model="notes">
	  </div>
	  <button type="submit" class="btn btn-info" ng-click='postUpdateNotes()'>Update notes</button>
	</form>
	<hr/>

    <form class="form-inline" role="form">
    <span style="font-size:16px;">ADD MINTUES</span>
	  <div class="form-group">
	    <label class="sr-only" for="exampleInputPassword2">Add minutes</label>
	    <input type="text" class="form-control" ng-model="addminutes" placeholder="Add minutes...">
	  </div>
	  <button type="submit" class="btn btn-info" ng-click='postAddMinutes()'>Add minutes</button>
	</form>
	<hr/>

</div> <!-- /container -->
	

    
	<script src="vendor/select2-3.4.6/select2.min.js"></script>

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="js/bootstrap.min.js"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <!-- <script src="js/ie10-viewport-bug-workaround.js"></script> -->
  </body>
</html>

Open in new window

0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 40616682
Well, the links I see on your page are like:
<a href="viewQueue.php">View Queue</a>

This has nothing to do with angular and clicking this link you should be redirected to this page.

Don't you have javascript errors on the page?
On the submit button you're calling a postUpdateUser() function that doesn't exist in the scope of the controller.
Instead what you have in the controller is a $postUpdateUser function that like this is arriving in the global scope.
0
 

Author Comment

by:DanteAdmin
ID: 40616923
Hi Alexandre

When I click on the link <a href="viewQueue.php">View Queue</a>

The URL just updates to "http://xxx.compute.amazonaws.com:8080/viewQueue.php" but sits on the same page, it simply replaces the URL

Yes just like you say I thought the same but after some reading up Angular.JS I thought binds everything and any call I make will replace the URL... and the code you sent me I've Googled as well to be the solution, but I'm still getting just the URL update

No Javascript errors when running Firebug to decode
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
In this tutorial viewers will learn how add a scalable full-width header using CSS3. Create a new HTML document with an internal stylesheet. Set a tiled background.:  Create a new div and name it Header. Position it with position:absolute at the top…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now