0

I am trying to show a <p> only in the HTTP protocol.

Here is what I have so far:

angular
.module('myApp',[])
.controller('myCtrl', ['$scope', '$window', function($scope, $window){

  $scope.name = 'Superhero';

  console.log('$window.location.protocol = ' + $window.location.protocol); // just checking

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

<div ng-app="myApp">

  <p ng-if="window.location.protocol === 'http:'">This needs to be shown in HTTP only.</p> <!-- doesnt work with $window either -->

  <div ng-controller="myCtrl">
    Hello, {{name}}!
  </div>

</div>

This snippet doesnt work in both HTTP and HTTPS.

I am pretty sure the problem is about accessing the window object.

How do I fix this?


Edit: Note that the <p> does not have any controller.

2 Answers 2

2

Because you can use nothing but scope properties in expressions. That's how they work. It is

$scope.$root.protocol = $window.location.protocol;

and

<p ng-if="protocol  === 'http:'">This needs to be shown in HTTP only.</p>
Sign up to request clarification or add additional context in comments.

2 Comments

@rahul-desai - even in this case <p> should be inside controller, right? how does this solve your problem?
Yes, @ManojShevate has the point. The code will be workable outside the controller (which is bad thing because the entire app should be controlled by 'ng-controller's or other directives) by assigning the variable to root scope, it will also be inherited by nested scopes.
1

Not sure why $window is not working, but here is the solution you can try -

use comparison operator inside controller and then add model in rootscope which is accessible out side the controller scope -

refer below code snippet, Hope this will solve your problem -

   angular
.module('myApp',[])
.controller('myCtrl', ['$scope', '$window','$rootScope', function($scope, $window,$rootScope){

  $scope.name = 'Superhero';
  $rootScope.httpOnly = $window.location.protocol === 'http:'; 

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">

  <p ng-if="$root.httpOnly">Outside Controller</p>

  <div ng-controller="myCtrl">
    Hello, {{name}}!
  </div>

</div>

Comments

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.