AngularJS1.5に再挑戦 その7 ForEach Loop in Angular JS Files
概要
AngularJS1.5に再挑戦 その7 ForEach Loop in Angular JS Files
参考動画・参考サイト
AngularJS — Superheroic JavaScript MVW Framework
ForEach Loop in Angular JS Files
- blog-detail.component.jsに追記する。
'use strict'; angular.module('blogDetail'). component('blogDetail', { templateUrl: '/templates/blog-detail.html', controller: function($routeParams, $scope){ var blogItems = [ {title: "Some Title", id:1, description: "This is a book", publishDate: "2017-01-08"}, {title: "Title2", id:2, description: "This is a book"}, {title: "Some Title3", id:3, description: "This is a book"}, {title: "Some Title4", id:4, description: "This is a book"}, ] // console.log($routeParams) $scope.title = "Blog " + $routeParams.id // notFound変数をtrueにしておく。一致したものは、falseにする。 $scope.notFound = true // forEach公文で、postのitemを総当たりして、一致したものをconsoleに表示する。 angular.forEach(blogItems, function(post){ if (post.id == $routeParams.id){ $scope.notFound = false $scope.post = post } console.log(post) }) // notFoundがtrueの場合 if ($scope.notFound){ console.log("Not found") } } });
- blog-detail.htmlに追記する。
<h1>{{ post.title }}</h1> <p>{{ post.description }}</p> <p>{{ post.publishDate }}</p>
- notFound=trueの時に、404ページに誘導する。blog-detail.component.jsにコードを追記する。
... controller: function($location, $routeParams, $scope){ ... if ($scope.notFound){ console.log("Not found") // change location。これには、$locationの継承が必要。 $location.path("/404") } ...
- $location便利やな〜!