AngularJS: route to /page/:id and show id's information? - javascript

I know it's a poorly constructed question, but I don't know how else to ask it.
I'm new to AngularJS, I'm trying to basically say "if a user clicks on "this" profile, go to /models/{{ model.id }} with model.id being the value of "this" profile that was clicked.
Basically, the main.html has only a bit of the information (a snippet, if you will), and when a profile is clicked it should go to /models/{{ model.id }} and then show the full profile as opposed to just a snippet.
I have it working so far in that the correct id shows up when hovering the profile link and it goes to the correct view with the correct url parameters, but how can I write data in the view that it goes to such that the data will be relevant to the ID that was clicked? I normally do this with PHP/Laravel and MySQL but I wanted to try it with Angular.
app.js:
'use strict';
angular
.module('swoleincApp', [
'ngRoute',
'ngSanitize',
'ngAnimate'
])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/models', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/models/:id', {
templateUrl: 'views/individual.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/models'
});
$locationProvider.html5Mode(true);
}]);
MainCtrl.js:
'use strict';
angular
.module('swoleincApp')
.controller('MainCtrl', ['$scope', '$http', MainCtrl]);
function MainCtrl($scope, $http) {
$http.get('storage/models.json').success(function(data) {
$scope.models = data;
});
}
main.html:
<div class="model-container" ng-repeat="model in models">
<a href="/models/{{ model.id }}">
<div class="row">
<div class="col-sm-2">
<div class="model-profile-image">
<img ng-src="{{ model.profileImage }}" width="100" height="100">
</div>
</div>
<div class="col-sm-8">
<div class="model-stats">
<h3>{{ model.name }}, {{ model.age }}, {{ model.height }}, {{ model.weight }}.</h3>
</div>
<div class="model-motto">
<p>{{ model.motto }}</p>
</div>
</div>
</div>
</a>
</div>
models.json (pretend the "other stuff" is meant for the individual profiles):
{
"1": {
"id": "1",
"profileImage": "../img/dom.jpg",
"name": "Dom",
"age": "19",
"height": "6'2",
"weight": "170lbs",
"motto": "My name is dom and I'm a 19 year old bodybuilder from Russia.",
"other": "other stuff",
"other": "other stuff",
"other": "other stuff",
"other": "other stuff",
},
"2": {
"id": "2",
"profileImage": "../img/Tom.jpg",
"name": "Tom",
"age": "21",
"height": "5'8",
"weight": "190lbs",
"motto": "I'm Tom. Everyone knows my name. Everyone knows my game.",
"other": "other stuff",
"other": "other stuff",
"other": "other stuff",
"other": "other stuff",
}
}

Use a different controller to simplify this. The parameter :id can be accessed using $routeParams injected into controller.
angular
.module('swoleincApp')
.controller('ProfileCtrl', ['$scope', '$http','$routeParams', ProfileCtrl]);
function ProfileCtrl($scope, $http, $routeParams) {
$http.get('storage/models.json').success(function(data) {
$scope.profile= data[$routeParams.id];
});
}
Be sure to update your routing config for this controller.
Normally you would create a service to handle retrieving the data and storing it. Have left $http in for now to keep it simple.
Suggest going through the phoneCat tutorial on documentations site.
Here's link to the routing section

All you need to do is to use the $RouteParams service. Here's the documentation on the AngularJS official website

Related

Can't seem to get this GET method to work properly in AngularJS

So I am building a portfolio page which uses a json file to store the project information. For some reason, I can't get the anything to show on ng-view, any ideas would be helpful!
Link to the Plunkr
Main Page:
<body ng-app="myApp">
<ng-view></ng-view>
</body>
Main View html:
<div class="container">
<div class="row">
<div ng-repeat="item in appList">
<a ng-href="{{item.link}}">
<img ng-src="{{item.image}}" />
<h4>
{{item.title}}
</h4>
</a>
</div>
</div>
</div>
Application JS:
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/',{
controller: "MainController",
templateUlr: "main.html"
});
})
app.controller('MainController', function($scope){
$scope.appList = {};
$http({
method: "GET",
url:"stuff.json"
}).success(function(data){
$scope.appList = data;
})
})
JSON file (just an example):
[{
"title": "Caption 1",
"image": "http://placehold.it/450x300?text=Image + 1",
"link": "#"
}, {
"title": "Caption 2",
"image": "http://placehold.it/450x300?text=Image + 2",
"link": "#"
}, {
"title": "Caption 3",
"image": "http://placehold.it/450x300?text=Image + 3",
"link": "#"
}]
I suspect there may be an issue with the json file, or how I am trying to access it. Anything will help at this point. (All dependencies are already added).
It is not templateUlr: instead it is : templateUrl:
You will need to inject $http and it will work.
Here is a working solution.
Add $http to controller
app.controller('MainController', function($scope,$http){
$scope.appList = {};
$http({
method: "GET",
url:"stuff.json"
}).success(function(data){
$scope.appList = data;
})
})

Show HTML from JSON with Angular

I'm new with Angular, and i am making an application with ionic. I can't show HTML from JSON in my view.
I searched previous questions but still doesn't work. The html code is written as text..
My code
HTML
<div ng-bind-html="bindHTML"></div>
Json
"usuarios": [
{
"nombre": "Name 1",
"description":"<p>Some HTML</p><p>More HTML</p>",
"id": 0
},
{
"nombre": "Name 2",
"description":"<p>Some HTML</p><p>More HTML</p>",
"id": 1
}
]
Controller
.controller('UserCtrl', ['$scope', '$http', '$state', function($scope, $http, $state) {
$http.get('js/data.json')
.success(function(data){
$scope.data = data.usuarios[$state.params.id];
$scope.bindHTML = $sce.trustAsHtml(data.description);
});
}])
Thanks.
I implemented a plunker to illustrate how this works. The only thing I didn't include is the ui.router $state stuff you are doing.
Controller
app.controller('MainCtrl', function($scope, $http, $sce) {
$http.get('data.json').success(function(data){
$scope.data = $sce.trustAsHtml(data.usuarios[0].descripcion);
});
});
View
<body ng-app="plunker" ng-controller="MainCtrl">
<p ng-bind-html="data"></p>
</body>
I'm not sure why yours wouldn't be working if you tried what was suggested in the thread that was marked as duplicate. That would leave me to believe it has something to do with the $state dependency, but hard to tell with out seeing your full app.

Passing data in between controller without help of url?

I am creating two page webapp using AngularJS.
my Json file is:
{
"data": [
{ "name": "bhav",
"id": 123
},
{"name": "bhavi",
"id": 1234
},
{"name": "bhavk",
"id": 1235
}
]
}
my app.js(Routing file is):
myApp = angular.module('myApp', ['slickCarousel',
'ngRoute',
'myAppControllers',
'myAppServices','swipeLi'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home-page.html',
controller: 'ProfileListCtrl',
}).
when('/profile/:typeofprofile', {
templateUrl: 'partials/profile-detail.html',
controller: 'ProfileDetailCtrl'
})
}]);
and my 1st page(home-page.html) is in given formate:
<div ng-repeat="data in data">
{{data.name}}
</div>
and on 2nd page(profile-details.html)
I want that id number of that profile considering I am using http.get request to pull data from Json file in controllers.
so please help me to fetch the id or name of clicked profile without passing through URL .
Note: I already look through ui-route link: Angular ui router passing data between states without URL but I didnt get that.
As you stated in the comments, you want to use $state.go() to pass your data.Using $state.go() to pass params is pretty simple as well. You need to inject ui.router in your application. I have created 2 partial views to show the passing of params where the params are passed from header.html to side.html.
Your JS will be something like below:
var app = angular.module('nested', ['ui.router']);
app.config(function($stateProvider,$locationProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/");
$stateProvider.state('top', {
url: "",
templateUrl: "header.html",
controller: 'topCtrl'
})
.state('top.side', {
url: '/app/:obj/:name',
templateUrl: "side.html",
controller: 'filterCtrl'
})
});
app.controller('topCtrl', function($scope,$state) {
$scope.goItem = function(){
$state.go('top.side',{obj:441,name:'alex'});
};
});
app.controller('filterCtrl', function($scope,$state) {
console.log(JSON.stringify($state.params));
$scope.params = $state.params;
});
Here is the working PLUNKER where you will find what you need to do regarding the views, controller and script:
http://plnkr.co/edit/M1QEYrmNcwTeFd6FtC4t?p=preview
I have provided the methods to pass $stateParams using both ui-sref and $state.go(). However, if you want to share the data among all the controllers. see my answer in this question:
Share Data in AngularJs

Creating a simple directive with JSON

I am creating a simple pattern library with an index page of HTML patterns, and individual pages for each pattern.
I am thinking that I should create a "pattern" directive that would include the template for the index page patterns. Like this:
<pattern></pattern>
which would show:
<section ng-repeat="pattern in patterns | orderBy:'title'" class="pattern-type" data-anchor="{{pattern.anchor}}" id="{{pattern.id}}">
<h3>{{pattern.title}} individuals/{{pattern.anchor}}</h3>
<div class="pattern-desc" ng-show="pattern.description">
<p>{{pattern.description}}</p>
</div>
<div class="pattern" ng-include="'individuals/' + {{pattern.anchor}}"></div>
<div class="pattern-status">
Date Posted: <span class="date"> {{pattern.updated | date:'yyyy-MM-dd'}}</span>
</div>
</section>
I would create a separate "individual" directive for the individual pattern display template. My app.js look like this:
app.directive('pattern', function() {
return {
restrict: 'E',
templateUrl: 'pattern.html',
controller: function() {
$http.get('assets/js/components.json')
.then(function(result) {
$scope.patterns = result.data;
});
},
controllerAs: 'patterns'
};
});
And my JSON looks like this:
[{
"id": "alerts",
"anchor": "alerts",
"title": "Alerts",
"description": "This is a desc",
"guidelines": "",
"updated": "2015-06-26"
},
{
"id": "buttons",
"anchor": "buttons",
"title": "Buttons",
"description": "",
"guidelines": "",
"updated": "2015-04-15"
}]
However nothing is showing up. What am I missing?
Your directive controller has missing $http & $scope dependency inside its function.
Code
controller: function($scope, $http) { //<-- added dependency here
$http.get('assets/js/components.json')
.then(function(result) {
$scope.patterns = result.data;
});
},
Working Plunkr

Angular in Jekyll/Github pages blog - blog post routing

I'm trying to incorporate Angular into my Jekyll/Github Pages blog. So far I've been able to set up the basic pages ("About", "Projects", and a list of posts), but the links for each post route to a non-angular page. I know I haven't set up the routes and partial quite right but am having trouble debugging. Any suggestions? Here's my code:
app.js:
'use strict';
var app = angular.module('myBlog', [
'ngRoute',
'ngResource',
'blogService',
'postService'
]);
app.config(function($routeProvider) {
$routeProvider
.when('/index', {
templateUrl: 'blog_overview.html',
controller: 'IndexCtrl'})
.when('/posts', {
templateUrl: 'blog_posts.html',
controller: 'BlogPostCtrl'})
.when('/posts/:link/', {
templateUrl: 'blog_post.html',
controller: 'BlogPostCtrl'})
.otherwise({redirectTo: '/index'});
})
.run();
controllers.js:
app.controller('BlogPostCtrl', ['$scope', '$resource', '$routeParams', 'Posts',
function($scope, $resource, $routeParams, Posts){
// $scope.templateUrl = ???
Posts.getPosts(function(data){
$scope.posts = data;
})
}])
directives.js:
'use strict';
angular.module('myBlog.directives', [])
.directive('markdown', function($http){
var converter = new Showdown.converter();
return{
restrict: 'A',
scope: { link:'#' },
link: function(scope, element, attrs){
attrs.$observe('link', function(link){
$http.get('/posts/' + link).success(function(response){
var htmlText = converter.makeHtml(response);
element.html(htmlText);
});
});
}
};
});
sample from blog_post.json
[
{
"title": "first post",
"slug": "2014-06-25-first-post",
"file": "app/js/posts/2014-06-25-first-post.md",
"tags": [
{"title" : "career"}
]
}]
blog_posts.html partial:
<div ng-controller="BlogPostCtrl">Posts</div>
<div ng-repeat="post in posts">
<h2>{{post.title}}</h2>
<div markdown link=""></div>
</div>
blog_post.html partial:
<div ng-controller="BlogPostCtrl">Posts</div>
<div ng-repeat="post in posts">
<p>{{post.file}}</p>
<div markdown link=""></div>
</div>
It looks like you're trying to reinvent the wheel. Delegating markdown parsing to client side is counterproductive.
Jekyll tries to remove all the unnecessary work on server side to allow sites to be light and performance oriented.
I understand that your work can be a proof of concept but I really don't get why you're trying to do it this way, because I guess that serving static pages is far more efficient than generating them client side.

Categories