I seem not to be able to show or hide ng-incude
directives
css:
#header, #mainarea {
display:none;
}
html:
<body ng-app="myApp" ng-controller="myCtrl">
<div id='login'></div>
<div id='header' ng-include="'views/header.html'"></div>
<div id='mainarea' ng-include="'views/mainarea.html'"></div>
<body>
js(myCtrl):
$scope.login = $('#login');
$scope.header = $('#header');
$scope.main = $('#mainarea');
if (correctUser) {
$scope.header.show();
$scope.main.show();
} else {
$scope.login.hide();
}
I have even included jQuery link before angular, but for some strange reason I cannot display the ng-include directives :(
can anyone help please?
There is a tricky problem here, and it's due to the fact that you will not be able to work with jQuery the way you are used to do it.
When controller is executed HTML for #header
div really looks like this:
<!-- ngInclude: 'views/header.html' -->
because ngInclude
takes it out of the DOM and appends when it's necessary (when template is loaded and ready to be displayed). As the result when you try to set up a reference to this element with jQuery like this
$scope.header = $('#header');
it doesn't find anything, because there is no such id in DOM yet.
So this is a good example why you should not work in jQuery-like style in Angular app. Instead, you should use ngShow/ngHide/ngIf directives:
<div ng-if="correctUser" ng-include="'views/header.html'"></div>
where correctUser
comes from controller:
$scope.correctUser = true;
You can do this using ng-if, without jquery and CSS display:none.
<body ng-app="myApp" ng-controller="myCtrl">
<div id='login' ng-if="login"></div>
<div id='header' ng-if="header" ng-include="'views/header.html'"></div>
<div id='mainarea' ng-if="main" ng-include="'views/mainarea.html'"></div>
<body>
and in your ctrl
$scope.login = true;
$scope.header = false;
$scope.main = false;
if(correctUser){
$scope.header = true;
$scope.main = true;
}else{
$scope.login = false;
}
Here is the JS FIDDLE based on your code.
My strong suggestion is dont mix and match jquery and angularjs. Try previous answers and try to stick purely with angularjs.
var myApp = angular.module('myApp',[]);
myApp.controller('myCtrl',function($scope){
$scope.correctUser = false;
$scope.lookfor = function(){
$scope.correctUser = !$scope.correctUser;
if($scope.correctUser){
$('#header').show();
$('#mainarea').show();
}else{
$('#header').hide();
$('#mainarea').hide();
}
}
})
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="lookfor()">Show Header</button>
<div id='header'>Header Template</div>
<div id='mainarea'>Main Area Template</div>
</div>
CSS
#header, #mainarea{
display:none;
}