Basic ng-show on div not working - javascript

I am just trying to get the ng-show tag working and to test it, I have a hard coded example and even this doesn't work (it is visible when the page loads). Code below.
#{
ViewBag.Title = "Secure Environment Flex";
}
<div class="row">
<div class="col-md-12">
<h3>Secure Environment</h3>
</div>
</div>
<div ng-controller="SEFlexHomeController" ng-show="false">
<div >
<div >
<ul>
<li>Jobs</li>
<li>Models</li>
<li>Administration</li>
</ul>
<div id="tabs-Jobs" >
<h1>Welcome to this jobs tab</h1>
</div>
<div id="tabs-Models">
<h1>Welcome to this models tab</h1>
</div>
<div id="tabs-Administration" >
<h1>Welcome to this administration tab</h1>
</div>
</div>
</div>
</div>
This is driving me mad, why is it still visible? Could something else in CSS be overriding it and if so how can I tell?
EDIT: Ok I got it working with a basic variable in scope like suggested. Now I'm trying to link it up to the actual action. My code retrieves a list of permissions in the background and once those are retrieved, I want to either display the page or an error depending on if the user is permissioned. Whats bizarre now is that I have two sections, page and error, one with ng-show matching the determination function and one with the negated function. But they are both showing? If I change them both to be just the function "isPermissioned" then the top one shows and the bottom doesn't, so it looks like they are getting different values from the same function. Could this be because one is executing before the other and when the background method updates the permissions, it isn't triggering the data binding?
New HTML is
<div ng-controller="SEFlexHomeController" ng-show="isPermissioned">
<div class="row" id="TabsSet1">
<div class="col-md-12">
<ul>
<li ng-show="AuthService.canRunFlexJobs || AuthService.canRunHighPriorityFlexJobs">Jobs</li>
<li ng-show="AuthService.canViewFlexModels">Models</li>
<li ng-show="AuthService.canAdministerFlex">Administration</li>
</ul>
<div id="tabs-Jobs" ng-show="AuthService.canRunFlexJobs || AuthService.canRunHighPriorityFlexJobs">
<h1>Welcome to this jobs tab</h1>
</div>
<div id="tabs-Models" ng-show="AuthService.canViewFlexModels">
<h1>Welcome to this models tab</h1>
</div>
<div id="tabs-Administration" ng-show="AuthService.canAdministerFlex">
<h1>Welcome to this administration tab</h1>
</div>
</div>
</div>
</div>
<div ng-show="!isPermissioned">
<h3>You have no permissions to view Secure Environment pages</h3>
</div>
JavaScript
app.controller("SEFlexHomeController", ["$scope", "$http", "$modal", "$log", "$element", "$rootScope", "AlertsService", "AuthService", "SEApplicationService", function ($scope, $http, $modal, $log, $element, $rootScope, AlertsService, AuthService, SEApplicationService) {
$rootScope.closeAlert = AlertsService.closeAlert;
$scope.isDataLoading = false;
$scope.AuthService = AuthService;
$scope.show = false;
$scope.isPermissioned = function() {
return AuthService.canAdministerFlex || AuthService.canViewFlexModels || AuthService.canRunFlexJobs || AuthService.canRunHighPriorityFlexJobs;
}
}
]);
Auth service
function AuthService($log, $http) {
var authService = {
canRunFlexJobs: false,
canRunHighPriorityFlexJobs: false,
canViewFlexModels: false,
canApproveFlexModels: false,
canAdministerFlex: false
};
authService.getUserClaims = function () {
$http.post("/Admin/Auth/GetUserClaims")
.success(function (response, status, headers, config) {
if (response) {
angular.forEach(response.data, function (item) {
if (item.Value === "SEFlexJobRunner")
authService.canRunFlexJobs = true;
if (item.Value === "SEFlexHighPriorityJobRunner")
authService.canRunHighPriorityFlexJobs = true;
if (item.Value === "SEFlexModelViewer")
authService.canViewFlexModels = true;
if (item.Value === "SEFlexModelApprover")
authService.canApproveFlexModels = true;
if (item.Value === "SEFlexAdministrator")
authService.canAdministerFlex = true;
});
}
})
.error(function (reason, status, headers, config) {
console.log(reason);
});
}
authService.getUserClaims();
return authService;
};

Well for your given code:
<div ng-controller="SEFlexHomeController" ng-show="show">
<div >
<div >
<ul>
<li>Jobs</li>
<li>Models</li>
<li>Administration</li>
</ul>
<div id="tabs-Jobs" >
<h1>Welcome to this jobs tab</h1>
</div>
<div id="tabs-Models">
<h1>Welcome to this models tab</h1>
</div>
<div id="tabs-Administration" >
<h1>Welcome to this administration tab</h1>
</div>
</div>
</div>
</div>
JS:
myAngularApp.controller('SEFlexHomeController', ['scope', function($scope) {
$scope.show = false;
// do stuff here
}]);

https://docs.angularjs.org/api/ng/directive/ngShow
<!-- when $scope.myValue is truthy (element is visible) -->
<div ng-show="myValue"></div>
<!-- when $scope.myValue is falsy (element is hidden) -->
<div ng-show="myValue" class="ng-hide"></div>

I assume you mean it's visible as the page loads and then disappears? If that's the case, you're going to want to also use ng-cloak.
Keep in mind that the css used by ng-cloak isn't available until Angular loads, so most put CSS like this in the header of their document.
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak
{
display: none !important;
}

Related

nested ng-repeat with json and rest api call back

I am trying to make a UI using list of product in a json(products.json) file on local and their availability in number from wp rest api call back in html(ionic) I have this:
Controller:
.controller('ShopCtrl', function($scope, $ionicActionSheet, BackendService, CartService, $http, $sce ) {
$scope.siteCategories = [];
$scope.cart = CartService.loadCart();
$scope.doRefresh = function(){
BackendService.getProducts()
.success(function(newItems) {
$scope.products = newItems;
console.log($scope.products);
})
.finally(function() {
// Stop the ion-refresher from spinning (not needed in this view)
$scope.$broadcast('scroll.refreshComplete');
});
};
$http.get("http://example.com/wp-json/wp/v2/categories/").then(
function(returnedData){
$scope.siteCategories = returnedData.data;
console.log($scope.siteCategories);
}, function(err){
console.log(err);
});
Template view:
<div ng-repeat = "product in products">
<div class="item item-image" style="position:relative;">
<img ng-src="{{product.image}}">
<div ng-repeat = "siteCategory in siteCategories">-->
<button class="button button-positive product-price" ng-click="addProduct(product)">
<p class="white-color product-price-price">post <b>{{siteCategory[$index].count}}</b></p>
</button>
</div>
</div>
<div class="item ui-gradient-deepblue">
<h2 class="title white-color sans-pro-light">{{product.title}} </h2>
</div>
<div class="item item-body">
{{product.description}}
</div>
</div>
so how can I achieve that? I tried to use nested ng-repeat but it didn't work out.

How to ng-if another div is visible

I have two lists of stuff using ng-repeat. Then I want it to say "empty" if there are no items in a list.
Here's the updated version:
<!-- First List -->
<div ng-repeat="request in requests" ng-if="request.condition1 == 'something'">
{{request}}
</div>
<div>Empty list</div>
<!-- Second List (both use requests array but have different conditions-->
<div ng-repeat="request in requests" ng-if="request.condition22222 == 'something else'">
{{request}}
</div>
<div>Empty list</div>
Try this:
(function(angular) {
'use strict';
angular.module('app', [])
.filter('decorate', function() {
return function(input, model) {
return input.filter(function(val){
return val[model.prop] == model.val;
});
};
}).controller('MyController', ['$scope', '$filter', function($scope, $filter) {
$scope.requests = [{name:'Tom', age:23},{name:'Henry', age:23},{name:'Max', age:33}];
$scope.$filter = $filter;
}])
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="MyController">
<div ng-init='items1=$filter("decorate")(requests, {prop:"age", val:23})'>First list(age=23):</div>
<div ng-repeat='item in items1' ng-if='items1.length > 0' >{{item | json}}</div>
<div ng-if='items1.length == 0'>Empty</div>
<br/>
<div ng-init='items2=$filter("decorate")(requests, {prop:"name", val:"Sam"})'>Second list(name=Sam):</div>
<div ng-repeat='item in items2' ng-if='items2'>{{item | json}}</div>
<div ng-if='items2.length == 0'>Empty</div>
</div>
</body>
You can check against the length of your list and show it conditionally:
<div ng-show="!requests.length">List is empty</div>
If you're working with an object you can use Object.keys although it may not be supported in some older browsers.

Compile error for Angular JS with js/ajax.js and index.html

When I compile my code there is an error with angular.
The code is written from a book, and it works when I load the page using the code at the end of the question.
There seems to be two issues from what I have read. Where do I put the $scope and $compile code?
Mostly, the question is how do I load a document ready trigger with a button for angular JS?
Or should I always load the angular js and hide the code?
<div id="myTabs">
<div class="menu">
<ul class= "tabs">
<li >LIST</li>
<li >GRID</li>
<li >GRID</li>
</ul>
</div>
<div class="container" style="margin-top:100px">
<div id="a">
</div>
<div id="b">
<ul class="gallery-items" id="grid">
</ul>
</div>
<div id="c" >
<div ng-controller="myController">
<div ng-repeat="item in items">
<img ng-src="{{item.img}}" />
{{item.description}}<br>
Rating: {{item.rating}} stars<br>
<span ng-repeat="idx in stars"
ng-class=
"{true: 'star', false: 'empty'}[idx <= item.rating]"
ng-click="adjustRating(item, idx)">
</span>
<hr>
</div>
</div>
</div>
</div>
ajax.js has a function that calls the #c tab to load
$(document).ready(function(){
$('#listC').click(function(){
angular.module('myApp', [])
.controller('myController', ['$scope', function($scope) {
$scope.stars = [1,2,3,4,5];
$scope.items = [100];
$.ajax({
type:'post',
url:'changeView.php',
data:{action: 'getGrid'},
success:function(data){
var data = JSON.parse(data);
for (i=0;i<data.length;i++) {
var imageLI = makeImage(data[i]['imageID'], data[i]['name'], data[i]['desc']);
$scope.items[i] = imageLI;
}
}
});
console.log($scope.items);
$scope.adjustRating = function(item, value){
item.rating = value;
};
}]);
});
$('#listC').trigger('click');
function makeImage(ID, name, description){
var image = {
description: description,
img: '../uploads/'+name,
rating: 4
}
return image;

How to implement multiple ng controllers with http calls in AngularJS?

In an app / on a page I have several places, where data should be loaded asynchronously. E.g.: a DIV with images and another one with cateories (for the navi). I implement it like this:
app.js
(function() {
var app = angular.module('portfolio', []);
app.controller('ProjectsListController', ['$http', function($http) {
var projectsList = this;
projectsList.projectsListData = [];
$http.get(config['api_server_url'] + '/projects').success(function(data) {
projectsList.projectsListData = data;
});
}]);
app.controller('NaviCategoriesController', ['$http', function($http) {
var categoriesList = this;
categoriesList.categoriesListData = [];
$http.get(config['api_server_url'] + '/categories').success(function(data) {
categoriesList.categoriesListData = data;
});
}]);
})();
list.phtml
<!-- projects -->
<div id="projects" ng-app="portfolio">
<div id="projectsList" ng-controller="ProjectsListController as projectsList">
<div class="projectItem" ng-repeat="projectItem in projectsList.projectsListData._embedded.projects">
<div class="project-image">
<img
ng-src="{{projectItem._embedded.images[0].src}}"
title="{{projectItem.title}} - {{projectItem._embedded.images[0].title}}"
alt="{{projectItem.title}} - {{projectItem._embedded.images[0].title}}"
/>
</div>
</div>
</div>
</div>
navi-categories .phtml
<!-- navi-categories -->
<div id="navi-categories" ng-app="portfolio">
<ul id="categoriesList" ng-controller="NaviCategoriesController as categoriesList">
<li class="categoryItem" ng-repeat="categoryItem in categoriesList.categoriesListData._embedded.categories">
{{categoryItem.short_name}}
</li>
</ul>
</div>
Every of these two blocks works fine. But I cannot use both at the same time. That means: The categories only get displayed, when the projects/images list is commented out (in the HTML) -- when I activate the list, the categories' HTTP request doesn't get sent anymore.
What am I doing wrong? How to implement this correctly?
Well... the problem is that they both have the ng-app="portfolio". You should wrap both components in one div with the ng-app="portfolio" attribute:
<div id="app" ng-app="portfolio">
<div id="projects">
<div id="projectsList" ng-controller="ProjectsListController as projectsList">
<div class="projectItem" ng-repeat="projectItem in projectsList.projectsListData._embedded.projects">
<div class="project-image">
<img
ng-src="{{projectItem._embedded.images[0].src}}"
title="{{projectItem.title}} - {{projectItem._embedded.images[0].title}}"
alt="{{projectItem.title}} - {{projectItem._embedded.images[0].title}}"
/>
</div>
</div>
</div>
</div>
<div id="navi-categories">
<ul id="categoriesList" ng-controller="NaviCategoriesController as categoriesList">
<li class="categoryItem" ng-repeat="categoryItem in categoriesList.categoriesListData._embedded.categories">
{{categoryItem.short_name}}
</li>
</ul>
</div>
</div>

How do I refresh my ng-repeat?

I have a controller (called "catalogueController") that manages my search box and my search page. I have the controller initially set the page to automatically call the search function defined in "catalogueController" when the app loads to pre-load my array of items (called Inventory) to be repeated via ng-repeat in the page.
The process runs like this:
1. I submit the search form.
2. "catalogueController" will send the search term to my factory (called "Search").
3. "Search" will have a function which will make a server call to query my database for that particular search.
4. The database will send the results of the search to the "Search" factory.
5. The "Search" factory will send the results to the "catalogueController" controller.
6. "catalogueController" will update the $scope.Inventory to be equal to the new result that I was received.
My problem is that ng-repeat does not refresh itself to display my new and updated $scope.Inventory array. $scope.Inventory definitely is updated (I have made sure of this through various console logs).
I have also tried to use $scope.$apply(). It did not work for me.
Thank you in advance for your help!
Here is my code:
HTML Template
<form role="search" class="navbar-form navbar-left" ng-controller="catalogueController" ng-submit="search(search_term)">
<div class="form-group">
<input type="text" placeholder="Search" class="form-control" ng-model="search_term">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
<main ng-view></main>
catalogue.html partial
<div id="main" class="margin-top-50 clearfix container">
<div ng-repeat="items in inventory" class="row-fluid">
<div class="col-sm-6 col-md-3">
<div class="thumbnail"><img src="image.jpg" alt="..." class="col-md-12">
<div class="caption">
<h3>{{ items.itemName }}</h3>
<p>{{ items.description }}</p>
<p>Buy <a href="#" role="button" class="btn btn-default">More Info</a></p>
</div>
</div>
</div>
</div>
"app.js" Angular App
var myApp = angular.module('qcbApp', ['ngRoute', 'ngCookies', 'appControllers']);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'html/partials/login.html',
controller: 'registrationController'
}).
when('/sign-up', {
templateUrl: 'html/partials/sign-up.html',
controller: 'registrationController'
}).
when('/catalogue', {
templateUrl: 'html/partials/catalogue.html',
controller: 'catalogueController'
}).
when('/', {
templateUrl: 'html/partials/qcbhome.html'
}).
otherwise({
redirectTo: '/'
});
}]);
"catalogueController" Controller
myApp.controller('catalogueController', ['$scope', 'Search', function($scope, Search) {
var time = 0;
var searchCatalogue = function(search) {
$scope.inventory = null;
console.log("Controller -- "+search);
Search.searchCatalogue(search)
.then(function(results) {
console.log(results);
$scope.inventory = results;
});
};
if(time == 0)
{
searchCatalogue('');
time++;
}
$scope.search = function(term) {
searchCatalogue(term);
}
}]);
"Search" Factory
myApp.factory('Search', ['$http', '$q', function($http, $q) {
function searchCatalogue(term) {
var deferred = $q.defer();
console.log("Factory -- "+term);
$http.post('/catalogue_data', {term: term}, {headers: {'Content-Type': 'application/json'}})
.success(function(result) {
console.log(result[0].SKU);
deferred.resolve(result);
console.log("Factory results -- "+result);
});
return deferred.promise;
}
return {
searchCatalogue: searchCatalogue
}; //return
}]);
I think the problem is the ng-repeat can not access the inventory in scope. You have to create a div which contains both the form and the ng-repeat.
The html should be:
<div ng-controller="catalogueController">
<!-- Move the controller from the form to parent div -->
<form role="search" class="navbar-form navbar-left" ng-submit="search(search_term)">
<div class="form-group">
<input type="text" placeholder="Search" class="form-control" ng-model="search_term">
</div>
<button type="submit" class="btn btn-default">Search</button>
</form>
<div id="main" class="margin-top-50 clearfix container">
<div ng-repeat="items in inventory" class="row-fluid">
<div class="col-sm-6 col-md-3">
<div class="thumbnail"><img src="image.jpg" alt="..." class="col-md-12">
<div class="caption">
<h3>{{ items.itemName }}</h3>
<p>{{ items.description }}</p>
<p>Buy <a href="#" role="button" class="btn btn-default">More Info</a></p>
</div>
</div>
</div>
</div>
</div>
I've seen the situation a few times where when you are updating a property directly on the $scope object there are interesting problems around databinding to that value (such as inventory). However if you databind to an object property of an object then the databinding works as expected. So for example use a property on $scope. I believe this is a copy by value vs copy by reference issue.
Update all your inventory references as follows
$scope.data.inventory = result;
Also don't forget to update your inventory reference in the html template:
<div ng-repeat="items in data.inventory" class="row-fluid">
Update: I made this plunk to figure it out - http://plnkr.co/edit/0ZLagR?p=preview
I think the primary problem is you have the controller specified twice. I removed it from the form and it started working.

Categories