Angular Directive Bug With View - javascript

I was doing a very quick exercise with angular directives. My code is very simple.
app.js:
var app = angular.module('readingList', []);
app.controller('BooksController', function($scope){
$scope.books = books;
$scope.genres = genres;
})
app.directive('bookGenres', function(){
return {
restrict: 'E',
templateURL: 'partials/book-genres.html'
};
});
var books = [{
title: 'ABCD',
author: 'E. Fgh',
isbn: '123414312341234',
review: 'Hello world',
rating: 4,
genres: {
'non-fiction': true, fantasy: false
}
}];
var genres = ["foo1","bar2","foo2","bar3"];
}
app.html:
<div class="row" ng-controller="BooksController">
<button class="btn btn-default">Create Review</button>
<hr />
<hr />
<ul class="list-unstyled col-sm-8" >
<li class="book row" ng-repeat="book in books">
<aside class="col-sm-3">
<a href="http://www.amazon.com/gp/product/{{book.isbn}}">
<img ng-src="http://images.amazon.com/images/P/{{book.isbn}}.01.ZTZZZZZZ.jpg" alt="" class="full"/>
</a>
<p class="goodRating rating">{{book.rating}}/5</p>
</aside>
<div class="col-sm-9 col-md-8">
<h3>
<a href="https://rads.stackoverflow.com/amzn/click/com/0553593714" rel="nofollow noreferrer">
{{book.title}}
</a>
</h3>
<cite class="text-muted">{{book.author}}</cite>
<p>{{book.review}}</p>
<!-- Put Genre Here -->
<book-genres></book-genres>
<ul class="list-unstyled">
<li ng-repeat="(genre, state) in book.genres">
<span class="label label-primary" ng-show="state === true">
{{genre}}
</span>
</li>
</ul>
</div>
</li>
</ul>
</div>
book-genres.html:
<ul class="list-unstyled">
<li ng-repeat="(genre, state) in book.genres">
<span class="label label-primary" ng-show="state === true">
{{genre}}
</span>
</li>
</ul>
Everything renders with the view except my book-genres directive. For reason, it doesn't work. I have checked the documentation. I checked other similar examples and nothing. If I can't get this directive to work, rendering out the other components such as the image is going to be a problem. I also checked the path of the partials views as well.

There's a couple possibilities here. You need to be sure to inject $scope into your controller:
app.controller('BooksController', ['$scope', function($scope) {
// do stuff
}]);
book.genres is not defined anywhere, so your ng-repeat has no items to display.
templateURL is also incorrect, it should be templateUrl.

Related

Ng-hide and show in ng-repeat

I am trying to get the button to toggle only on the one clicked, but as I am using ng-repeat, it all changes together. How do i fix it so that it would only change on the one clicked?
HTML:
<ul>
<li class="displaySubCategory" ng-repeat="communityTheme in community | startFrom:currentPage*pageSize | limitTo:pageSize">
<div class="categoryImg">
<img src="img/csvIcon.png" />
<img src="img/shpIcon.png" />
</div>
<div class="categoryDesc">
<p>{{communityTheme.THEMENAME}}</p>
<a ng-href="https://assets.onemap.sg/shp/{{SHPFile}}" ng-click="getSHP(communityTheme.QUERYNAME)" target="_blank" download>SHP</a> |
<a ng-href="https://assets.onemap.sg/kml/{{KMLFile}}" ng-click="getKML(communityTheme.QUERYNAME)" target="_blank" download>KML</a> |
View on Map
Remove Marker
<!-- <a href="" ng-click="getData(communityTheme.QUERYNAME)" download>View Data</a> -->
</div>
</li>
</ul>
JS:
$scope.viewMarker = true;
$scope.getMapData = function (msg) {
$scope.viewMarker = !$scope.viewMarker;
}
Before:
After:
Modified code:
$scope.viewMarker = true;
$scope.getMapData = function (msg, passedIndex) {
if($scope.community[passedIndex].visibility)
{
$scope.community[passedIndex].visibility =false;
} else {
$scope.community[passedIndex].visibility = true;
}
$scope.viewMarker = !$scope.viewMarker;
<ul>
<li class="displaySubCategory" ng-repeat="communityTheme in community | startFrom:currentPage*pageSize | limitTo:pageSize">
<div class="categoryImg">
<img src="img/csvIcon.png" />
<img src="img/shpIcon.png" />
</div>
<div class="categoryDesc">
<p>{{communityTheme.THEMENAME}}</p>
<a ng-href="https://assets.onemap.sg/shp/{{SHPFile}}" ng-click="getSHP(communityTheme.QUERYNAME)" target="_blank" download>SHP</a> |
<a ng-href="https://assets.onemap.sg/kml/{{KMLFile}}" ng-click="getKML(communityTheme.QUERYNAME)" target="_blank" download>KML</a> |
View on Map
Remove Marker
<!-- <a href="" ng-click="getData(communityTheme.QUERYNAME)" download>View Data</a> -->
</div>
</li>
</ul>
this should help clarify...
var app = angular.module("test", []);
app.controller("myCtrl", function($scope) {
$scope.community = [
{ THEMENAME:"Milk", QUERYNAME:"Milk", visibility:true}
, { THEMENAME:"Bread", QUERYNAME:"Milk", visibility:true}
, { THEMENAME:"Cheese", QUERYNAME:"Milk", visibility:true}
];
$scope.getMapData = function(passedQueryName, passedIndex){
/*do what you were doing, just add this one more point*/
if($scope.community[passedIndex].visibility) {$scope.community[passedIndex].visibility =false;}
else {$scope.community[passedIndex].visibility = true;}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="test">
<div ng-app="myShoppingList" ng-controller="myCtrl">
<div ng-repeat="communityTheme in community ">
{{x}}
<div class="categoryDesc">
<p>{{communityTheme.THEMENAME}} # {{$index}}</p>
<a ng-href="https://assets.onemap.sg/shp/{{SHPFile}}" ng-click="getSHP(communityTheme.QUERYNAME)" target="_blank" download>SHP</a> |
<a ng-href="https://assets.onemap.sg/kml/{{KMLFile}}" ng-click="getKML(communityTheme.QUERYNAME)" target="_blank" download>KML</a> |
View on Map
Remove Marker
<!-- <a href="" ng-click="getData(communityTheme.QUERYNAME)" download>View Data</a> -->
</div>
</div>
</div>
<p>So far we have made an HTML list based on the items of an array.</p>
</div>
You can try using it like the below code where we'll be creating dynamic variable 'viewMarker' in the same object and to consider it's default value as 'false' and to toggle it in the getMapData function by inverting its value.
Template:
<ul>
<li class="displaySubCategory" ng-repeat="communityTheme in community | startFrom:currentPage*pageSize | limitTo:pageSize">
<div class="categoryImg">
<img src="img/csvIcon.png" />
<img src="img/shpIcon.png" />
</div>
<div class="categoryDesc">
<p>{{communityTheme.THEMENAME}}</p>
<a ng-href="https://assets.onemap.sg/shp/{{SHPFile}}" ng-click="getSHP(communityTheme.QUERYNAME)" target="_blank" download>SHP</a> |
<a ng-href="https://assets.onemap.sg/kml/{{KMLFile}}" ng-click="getKML(communityTheme.QUERYNAME)" target="_blank" download>KML</a> |
View on Map
Remove Marker
<!-- <a href="" ng-click="getData(communityTheme.QUERYNAME)" download>View Data</a> -->
</div>
</li>
</ul>
Controller:
$scope.getMapData = function (obj) {
obj.viewMarker = !obj.viewMarker;
}
As i see now you are using the same variable to handle the toggling part. you should have an individual variable with a boolean value to handle the toggling so that you can handle each element individually.
DEMO

Pass a value to another controller which executes first

I have two controllers headerController, aboutController.
headerController -> To maintain the navigation and redirection
aboutController -> works when about-us page loads.
My issue is I have to update the headerController variable value when aboutController loads. i.e When about us page loads, the navigation about-us should active, similar to all the pages.
This is my code:
app.service('shareService', function () {
var data;
return {
getProperty: function () {
return data;
},
setProperty: function (value) {
data = value;
}
};
});
app.controller('headerController', function ($scope, shareService) {
$scope.navigation = [
{url: '#!/home', name: 'Home'},
{url: '#!/about-us', name: 'About Us'},
{url: '#!/services', name: 'Services'}
];
var data = shareService.getProperty();
console.log(data);
$scope.selectedIndex = 0;
$scope.itemClicked = function ($index) {
console.log($index);
$scope.selectedIndex = $index;
};
});
app.controller('aboutController', function ($scope, shareService) {
console.log('test');
$scope.selectedIndex = 1;
shareService.setProperty({navigation: $scope.selectedIndex});
});
header.html:
<header ng-controller="headerController">
<div class="header">
<div class="first-half col-md-6">
<div class="row">
<div class="logo">
<img src="assets/img/logo.png" alt=""/>
</div>
</div>
</div>
<div class="second-half col-md-6">
<div class="row">
<div class="social-share">
<ul id="social-share-header">
<li><i class="fa fa-facebook" aria-hidden="true"></i></li>
<li><i class="fa fa-twitter" aria-hidden="true"></i></li>
<li><i class="fa fa-google-plus" aria-hidden="true"></i></li>
</ul>
</div>
</div>
</div>
<nav>
<ul ng-repeat="nav in navigation">
<li class="main-nav" ng-class="{ 'active': $index == selectedIndex }"
ng-click="itemClicked($index)">
{{nav.name}}
</li>
</ul>
</nav>
</div>
</header>
index.html
This is how my template works.
<body ng-app="myApp">
<section class="first-section">
<div ng-include="'views/header.html'"></div>
</section>
<section class="second-section">
<div ng-view></div>
</section>
<section class="last-section">
<div ng-include="'views/footer.html'"></div>
</section>
</body>
Update 1: Added index.html file.
Update 2: Issue explanation: If I run directly to the about us page, then still the home navigation is on active. But it should be About us
What is you are looking for is event based communication between your controllers. This can be easily done using. $rootScope.$on, $rootScope.$emit and $rootScope.$broadcast. Since explaining all three of them in this answer will be overkill. Kindly go through this article

Use NG-CLICK to change class on a clicked element

I am creating dynamic tabs using ajax data loaded via the WordPress REST-API. Everything is working, but I need to add a class to the active tab in order to use CSS transforms on it.
I would appreciate any suggestions. I know how to use ng-class when clicking one element affects another, but not when it affects the clicked element. It's also worth noting I am using the 'as' syntax for the ng-controller.
JAVASCRIPT:
var homeApp = angular.module('homeCharacters', ['ngSanitize']);
homeApp.controller('characters', function($scope, $http) {
$scope.myData = {
tab: 0
}; //set default tab
$http.get("http://bigbluecomics.dev/wp-json/posts?type=character").then(function(response) {
$scope.myData.data = response.data;
});
});
homeApp.filter('toTrusted', ['$sce',
function($sce) {
return function(text) {
return $sce.trustAsHtml(text);
};
}
]);
HTML:
<div class="more_comics_mobile">More Comics <img src="./images/white-arrow.png" />
</div>
<section class="characters" ng-app="homeCharacters" ng-controller="characters as myData">
<div class="char_copy" ng-repeat="item in myData.data" ng-bind-html="item.content | toTrusted" ng-show="myData.tab === item.menu_order">
{{ item.content }}
</div>
<div class="char_tabs">
<nav>
<ul ng-init="myData.tab = 0" ng-model='clicked'>
<li class="tab" ng-repeat="item in myData.data">
<a href ng-click="myData.tab = item.menu_order">
<img src="{{ item.featured_image.source }}" />
<h3>{{ item.title }}</h3>
</a>
</li>
</ul>
</nav>
</div>
</section>
I am trying to add the class to the li element. I appreciate any help!
You can use ng-class like
<li class="tab" ng-repeat="item in myData.data" ng-class="{'active' : item.menu_order == myData.tab}"></li>
For more options you can visit
https://docs.angularjs.org/api/ng/directive/ngClass
<div class="more_comics_mobile">More Comics <img src="./images/white-arrow.png" />
</div>
<section class="characters" ng-app="homeCharacters" ng-controller="characters as myData">
<div class="char_copy" ng-repeat="item in myData.data" ng-bind-html="item.content | toTrusted" ng-show="myData.tab === item.menu_order">
{{ item.content }}
</div>
<div class="char_tabs">
<nav>
<ul ng-init="myData.tab = 0" ng-model='clicked'>
<li class="tab" ng-click="activate($index)" ng-repeat="item in myData.data">
<a href ng-click="myData.tab = item.menu_order">
<img src="{{ item.featured_image.source }}" />
<h3>{{ item.title }}</h3>
</a>
</li>
</ul>
</nav>
</div>
</section>
in your js
$scope.activate = function(index){
document.getElementsByClassName.setAttribute("class","tab");
document.getElementsByClassName[index].setAttribute("class","tab active");
}

custom angular directive is not rendering

I am trying to create a directive, but for some reason nothing is rendering. The screen is blank.
index.html
<div class="main" ng-controller="MainController">
<div class="container">
<div class="content">
<program-listing listing="program"></program-listing>
</div>
</div>
</div>
<!-- Controllers -->
<script src="js/controllers/MainController.js"></script>
<script src="js/directives/programListing.js"></script>
js/controllers/mainController.js
app.controller('MainController', ['$scope', function($scope) {
$scope.program = {
series: "Sherlock",
series_img: "img/sherlock.jpg",
genre: "Crime drama",
season: 3,
episode: "The Empty Hearse",
description: "Two years after his reported Reichenbach Fall demise, Sherlock, who has been cleared of all fraud charges against him, returns with Mycroft's help to a London under threat of terrorist attack. John has moved on and has a girlfriend, Mary Morstan. Sherlock enlists Molly to assist him, but when John is kidnapped by unknown assailants and is rescued by Sherlock and Mary, John returns to help find the terrorists and an underground plot to blow up the Houses of Parliament during an all night sitting on Guy Fawkes Night.",
datetime: new Date(2014, 11, 31, 21, 00, 00, 00)
};
}]);
js/directives/programListing.js
app.directive('programListing', function(){
return{
restrict: 'E',
scope: {
listing: '='
},
templateUrl: 'js/directives/programListing.html'
};
});
js/directives/programListing.html
<div class="row">
<div class="col-md-3" class="series_img">
{{ listing.series_img }}
</div>
<div class="col-md-6">
<h1 class="series">{{listing.series}}</h1>
<h2 class="episode">{{listing.episode}}</h2>
<p class="description">{{listing.description}}</p>
</div>
<div class="col-md-3">
<ul class="list-group">
<li class="list-group-item"><span>Date:</span> {{listing.datetime | date:'mediumDate' }} </li>
<li class="list-group-item"><span>On air:</span> {{ listing.datetime | date:'EEEE' }} </li>
<li class="list-group-item"><span>Time:</span>{{ listing.datetime | date:'shortTime' }} </li>
<li class="list-group-item"><span>Season:</span> {{listing.season}} </li>
<li class="list-group-item"><span>Genre:</span>{{ listing.genre }} </li>
</ul>
</div>
</div>
Why isn't anything rendering?
templateUrl is an argument to your directive. You should not have it in your scope. Your directive doesn't know what to render!
scope = {...},
templateUrl = '...'

Sorting object in angularjs whilst paginating

I have data coming from a server that I want to display. This data is being paginated and also sorted. The relevant part of the controller is as follows:
appControllers.controller('PostsCtrl',
['$scope', 'Restangular', 'messageCenterService',
'$location', '$anchorScroll',
'$filter',
function ($scope, Restangular, messageCenterService,
$location, $anchorScroll, $filter) {
// Get all posts from server.
var allPosts = Restangular.all('api/posts');
allPosts.getList().then(function (posts) {
$scope.posts = posts;
$scope.predicate = 'rank';
$scope.reverse = false;
$scope.itemsPerPage = 10;
$scope.currentPage = 1;
$scope.totalItems = $scope.posts.length;
$scope.pageCount = function () {
return Math.ceil($scope.totalItems / $scope.itemsPerPage);
};
$scope.$watch('currentPage + itemsPerPage',
function () {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.position = (10 * ($scope.currentPage - 1));
$scope.filteredPosts = $scope.posts.slice(begin, end);
$location.hash('top');
// call $anchorScroll()
$anchorScroll();
});
});
Here is the html:
<li class="list-group-item" ng-repeat="post in filteredPosts | orderBy:predicate:reverse">
<div class="row-fluid">
<div class="col-sm-1 ">
<p style="margin-top: 1em">{{($index + 1) + position}}.</p>
</div>
<div class="col-sm-1 v-center">
<i class="fa fa-angle-up"></i> <br />
<small>{{post.votes}}votes</small> <br />
<i class="fa fa-angle-down"></i>
</div>
<div class="col-sm-8">
<h4><a href={{post.url}}>{{post.title}}</a></h4>
<div>
<ul class="list-inline">
<li ng-repeat="tag in post.tags">
<span class="fa fa-tag"></span>
<button ng-click="getTags(tag.id)">{{tag.name}}</button>
</li>
</ul>
<div>
<em>{{ post.created_at | timeAgo}}</em>
by <cite>{{post.author.username}}</cite>
</div>
<div>
<a href ng-click="select(post)">
<span class="fa-stack fa-2x">
<i class="fa fa-comment fa-stack-2x"></i>
<strong class="fa-stack-1x fa-stack-text fa-inverse">
{{post.comments.length}}
</strong>
</span>
</a>
</div>
</div>
<div class="panel" ng-show="isSelected(post)">
<ul class="nav nav-list" ng-repeat="comment in post.comments">
<li class="list-group-item">
<strong><cite>{{comment.author.username}}</cite></strong>
{{comment.updated_at | timeAgo }}
<p>{{comment.message}}</p>
</li>
</ul>
<form name="CommentForm" novalidate role="form" ng-if="user.isLoggedIn" ng-submit="CommentForm.$valid && comment(post)">
<label for="InputComment">Add a Comment</label>
<textarea ng-model="newComment.message" class="form-control" id="InputComment" rows="3" required></textarea>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</li>
<pagination total-items="totalItems" items-per-page="itemsPerPage"
ng-model="currentPage" ng-change="pageChanged()"></pagination>
I need some help with figuring out how to filter the order in which the data is displayed on the page. I have read other questions which ask about sorting but I did not see any where the content is also paginated with angularjs. The question I have is how do I do a live filter considering that I have objects coming back from the server and the content is then paginated?
You could create a paging filter, and combine it with orderBy to simulate filteredPosts.
app.filter('page', function () {
return function (input, start, end) {
return input.slice(start, end);
};
});
Then you can apply both filters in your template.
ng-repeat="post in posts | orderBy:predicate:reverse | page:begin:end"
You can use the orderBy filter also programmatically to sort your array
$scope.posts = posts;
$scope.posts=$filter('orderBy')($scope.posts,'rank',false );
$scope.itemsPerPage = 10;
...
$filter u have already as a dependency in your controller

Categories