Angular JS - Changing state depending on item clicked - javascript

I want to display content beneath a table, from a JSON file, relative to to item the user clicked on in the table
Example:
JSON file
{
"patentInfo": [
{
"name": "item1",
"cost": "$33",
"date": "13/06",
},
{
"name": "item2",
"cost": "$29",
"date": "02/02",
}
]
}
View - table
click on item 1 > DISPLAY price:$33, date:13/06
click on item 2 > DISPLAY price:$29, date:02/02
I asked this question last week but didn't get a response as I don't think I made it too clear. I'm using ui-view to display content, and it is the state patents.list.item URL that needs to be relative, dependent on what the user clicked on. Any ideas on how to achieve this?
var app = angular.module('myApp', ['ngRoute', 'angularMoment', 'ui.router', "chart.js"]);
app.config(['$stateProvider', '$locationProvider', '$urlRouterProvider', function($stateProvider, $locationProvider, $urlRouterProvider ) {
$urlRouterProvider
.when('', '/patents/list-patents')
.when('/', '/patents/list-patents')
.when('/patents', '/patents/list-patents')
.when('/transactions', '/transactions/current-transactions')
.otherwise('/patents/list-patents');
$stateProvider
.state("patents", {
url: "/patents",
templateUrl: "templates/patents/patent-nav.htm",
controller: "patentCtrl"
})
.state("patents.list", {
url: "/list-patents",
templateUrl: "templates/patents/list/list-patents.htm",
controller: "patentCtrl"
})
.state("patents.list.item", {
url: "/patent-item",
templateUrl: "templates/patents/list/patent-item.htm",
controller: "patentCtrl"
})
Controller
app.controller('patentCtrl', ['$scope', '$http', 'patentTabFactory', 'loadPatents', '$stateParams', 'patentService', function($scope, $http, patentTabFactory, loadPatents, $stateParams, patentService) {
patentService.items.then(function (patents) {
$scope.items = patents.data;
console.log($scope.patents);
$scope.patents = patents.data[patentService.getPatentItem($scope.items, "aid", $stateParams.id)];
});
$scope.patent={id:null,applicationNumber:'',clientRef:'',costRenew:'',renewalDate:'',basketStatus:'', costEnd: '', nextStage:''};
$scope.patents=[];
$scope.submit = $scope.submit;
$scope.remove = $scope.remove;
$scope.fetchAllPatents = function(){
loadPatents.fetchAllPatents()
.then(
function(d) {
$scope.patents = d;
},
function(errResponse){
console.error('Error while fetching Users');
}
);
}
$scope.fetchAllPatents();
$scope.deletePatent = function(id){
loadPatents.deletePatent(id)
.then(
$scope.fetchAllPatents,
function(errResponse){
console.error('Error while deleting Patent');
}
);
}
$scope.submit = function() {
if($scope.patent.id===null){
console.log('Saving New User', $scope.patent);
loadPatents.createPatent($scope.patent);
}
console.log('User updated with id ', $scope.patent.id);
}
$scope.remove = function(id){
console.log('id to be deleted', id);
if($scope.patent.id === id) {//clean form if the patent to be deleted is shown there.
reset();
}
$scope.deletePatent(id);
}
$scope.tabs = patentTabFactory.tabs;
$scope.currentTab = patentTabFactory.currentTab;
// $scope.isActiveTab = patentTabFactory.isActiveTab();
$scope.onClickTab = function(currentTab) {
patentTabFactory.onClickTab(currentTab);
$scope.currentTab = patentTabFactory.currentTab;
};
$scope.isActiveTab = function(tabUrl) {
return tabUrl == patentTabFactory.currentTab;
}
}]);
list-patents view
<div class="row">
<div class="col-md-12">
<table class="table table-bordered table-striped text-md-center">
<thead class="thead-inverse">
<tr>
<td ng-click="patentAppOrder()" class="align-middle">Application No. </td>
<td class="align-middle">Client Ref</td>
<td class="align-middle">Cost to renew</td>
<td class="align-middle">Basket</td>
<td class="align-middle">Remove</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in patents">
<td><a ui-sref="patents.list.item">{{x.applicationNumber}}</a></td>
<td ng-bind="x.clientRef"></td>
<td ng-bind="x.costToRenew">$</td>
<td ng-bind="x.renewalDueDate"></td>
<td><button type="button" class="btn btn-danger" ng-click="remove(x.id)">Remove</button></td>
</tr>
</tbody>
</table>
<div ui-view></div>
</div>
</div>
<div ui-view></div>
patent item view
<div id="tabs">
<ul>
<li ng-repeat="tab in tabs"
ng-class="{active:isActiveTab(tab.url)}"
ng-click="onClickTab(tab)">{{tab.title}}</li> <!--applies active to the returned tab url -->
</ul>
<div id="mainView">
<div class="row">
<div ng-include="currentTab"></div>
</div>
</div>
</div>
<script type="text/ng-template" id="patent-info.htm">
<div class="col-md-6 text-xs-center">
<h2>Application Number</h2>
<table class="table table-striped">
<tbody>
<table>
<tr ng-repeat="(x, y) in patents">
<td ng-repeat="x.id in patents"></td>
<td>{{y.applicationNumber}}</td>
</tr>
</table>
</tbody>
</table>
</div>
<div class="col-md-6 text-xs-center">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
</p>
</div>
</script>
<script type="text/ng-template" id="cost-analysis.htm">
<div class="col-md-6 text-xs-center" ng-controller="LineCtrl">
<h2>Cost Analysis</h2>
<canvas class="chart chart-line" chart-data="data" chart-labels="labels"
chart-series="series" chart-click="onClick"></canvas>
</div>
</script>
<script type="text/ng-template" id="renewal-history.htm">
<div class="col-md-6 text-xs-center">
<h2>Renewal History</h2>
<p>In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor..</p>
</div>
</script>

What you have to do first is to add a dynamic URL parameter to the route which is supposed to display information about a selected patent and give it another controller.
.state("patents.list.item", {
url: "/patent-item/:name",
templateUrl: "templates/patents/list/patent-item.htm",
controller: "patentDetailsCtrl"
})
Then when you are navigating to that patent, you have to include the name (assuming that is a unique identifier) in the link.
<td><a ui-sref="patents.list.item({ name: x.name })">{{x.applicationNumber}}</a></td>
After that in your patentDetailsCtrl, you can fetch information about the patent from the JSON file and display it.
Alternative Solutions
Another solution would be handle it in your patentCtrl without an additional (patents.list.item) route. But I would not recommend that approach.
You could also use components if you are using AngularJS v1.5+. To learn more about components, see the official documentation.

Related

Cannot Display Object Contents - AngularJS

I am trying to make an app that will display the job details in the modal window, depending on the template that is selected. For this I have combined ui.bootstrap and ui.router . But for some reason, I cannot manage to display the objects as I would want to. I know that $http.get is working, as when I do the console.log(specs), the object is displayed.
This is my code:
HTML
<div class="car-up" ng-controller="carCtrl">
<script type="text/ng-template" id="careersTpl.html">
<div class="closer">
<span class="close-me" ng-click="ok()">X</span>
</div>
<div class="modal-body">
<span>{{placeholder}}</span>
</div>
<div class="modal-body modtwo">
<ul>
<li><a ui-sref="sales">Sales Department</a></li>
</ul>
<ul>
<li><a ui-sref="webd">Web Developer</a></li>
<li><a ui-sref="crm">Client Relationship Manager</a></li>
<li></li>
</ul>
<div class="show-me" ui-view></div>
</div>
</script>
<button class="btn" ng-click="open()">Open</button>
</div>
app.js
var app = angular.module('carApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap', 'ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('webd', {
url: "/web-developer",
templateUrl: "templates/web-developer.html",
})
.state('crm', {
url: "/crm",
templateUrl: "templates/crm-uk.html"
})
}]);
ctrl.js
app.controller('carCtrl', function($scope, $http, $uibModal) {
$http.get('jobs.json').then(function(response) {
$scope.placeholder = response.data.default;
$scope.specs = response.data.specs;
$scope.open = function() {
var modalContent = $uibModal.open({
templateUrl: 'careersTpl.html',
controller : 'modalContentCtrl',
controllerAs: '$ctrl',
size: 'lg',
backdropClass: 'backdropOver',
openedClass: 'modal-opened',
resolve: {
items: function() { return $scope.specs; },
items2: function() { return $scope.placeholder;}
}
})
console.log($scope.placeholder);
console.log($scope.specs);
console.log($scope.specs.crm);
}
});
});
app.controller('modalContentCtrl', function($scope, $uibModalInstance, items, items2) {
$scope.specs = items;
$scope.placeholder = items2;
$scope.ok = function() {
$uibModalInstance.close();
}
});
crm-uk.html
<div ng-repeat="(k, v) in specs.crm">
<h3>{{v["job-title"]}}</h3>
<p>{{v["job-body"]}}</p>
Apply Here:
<p>{{v["job-apply"]}}</p>
</div>
web-developer.html
<div ng-repeat="(k, v) in specs.web-dev">
<h3>{{v["job-title"]}}</h3>
<p>{{v["job-body"]}}</p>
Apply Here:
<p>{{v["job-apply"]}}</p>
</div>
JSON
{
"default":"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"specs":{
"web-dev":{
"job-title":"Web Developer",
"job-body":"Lorem Ipsum Body Text",
"job-apply":"applink"
},
"crm":{
"job-title":"Client Relationship Manager",
"job-body":"Lorem Ipsum CRM Text",
"job-apply":"applylink"
}
}
}
I believe something is wrong with my .json file or how I am accessing it, but cannot figure out what.
Can someone please help?
thanks.
First best to change the JSON structure as following:
{
"default": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"specs": {
"web-dev": [{
"job-title": "Web Developer",
"job-body": "Lorem Ipsum Body Text",
"job-apply": "applink"
}],
"crm": [{
"job-title": "Client Relationship Manager",
"job-body": "Lorem Ipsum CRM Text",
"job-apply": "applylink"
}]
}
}
Make the "crm" as a list of multiples.
Then in the view file, you can loop the "crm" specs list.
<div ng-repeat="item in specs.crm">
{{item['job-title']}}<br/>
{{item['job-body']}}<br/>
{{item['job-apply']}}<br/>
</div>
Or use {{::item['job-title']}} for single data binding to limit digest cycles
Working Plunkr here
Please note only updated for 'CRM'

Redirection not working

i have a button with ng-click which i pass an object by paramater to a function, that function have to redirect me to another page with the id of the object i've passed to it, and another controller receive it, search it in the bd and show it in my view, but the button it's not working, it just redirrects me to the $routeProvicer.otherwise('/') the home. But if I type manualy localhost:3000/admin/1241245124 <= the id it works perfect...
Any help is apreciated, i've leave you down here my code.
admin.html
<h1>Admin Panel</h1>
<hr>
<div class="row">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Productos</h3>
</div>
<div class="panel-body">
<table class="table">
<tr>
<td>Titulo</td>
<td>Tipo</td>
<td>Autor</td>
<td>Creado</td>
<td>Acciones</td>
</tr>
<tr ng-repeat="product in products">
<td><a ng-href="{{}}">{{product.nombre}}</a></td>
<td>{{product.tipo}}</td>
<td>{{product.autor}}</td>
<td>{{product.creado | date}}</td>
<td>Borrar Editar</td>
</tr>
</table>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Articulos</h3>
</div>
<div class="panel-body">
Panel content
</div>
</div>
</div>
</div>
admin.js
'use strict';
angular.module('myApp.admin', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/admin', {
templateUrl: 'admin/admin.html',
controller: 'AdminCtrl'
});
$routeProvider.when('#/admin/:id', {
templateUrl: 'admin/edit.html',
controller: 'AdminEditCtrl'
});
}])
.controller('AdminCtrl', function($scope, $http,librosFactory, $location) {
librosFactory.getLibros().success(function(libros){
$scope.products = libros;
});
$scope.deleteBook = function(book){
console.log(book);
librosFactory.deleteBook(book).success(function (book,err) {
if (err) console.log(err);
else console.log("libro borrado");
});
};
$scope.editBook = function (book) {
if(book._id) {
console.log(book);
$location.url('#/admin/'+book._id);
}
else {
console.log('erroror');
}
}
})
.controller('AdminEditCtrl', function ($scope, $routeParams, librosFactory) {
librosFactory.searchById($routeParams.id).success(function (book, err) {
if(err) console.log(err);
console.log(book)
$scope.product = book;
})
});
Try removing the # from the href attribute in the <a> let it be href=""

Simple ngTable with large JSON not showing any data in cells

I have a large json file almost 5 MB in size with the following array format.
There are about 3000 records.
I am using microsoft mvc 4 and angular + ngTable to display this data in the front end. It needs to be searchable and sortable on all columns.
The server side code does not take any arguments and returns all 3000 records in the format below.
{
"MR": "Inact",
"EncType": null,
"ClientAlias": 111020.0,
"OrgName": "Zic",
"CharacterAlias": null,
"Account#": 30645147.0,
"MRN": null,
"PlanCode": null,
"Address": "PO Box 123456",
"City": "Richmond ",
"St": "VA",
"ZIP": 23298.0,
"ContactName": "Jonny J",
"Fax": "(111) 111-1111",
"PHONE": "pager 111-1111",
"CriticalValueNotification": null,
"ClientPracticeTesting": null,
"Doctor": "John Smith",
"BeginDate": 36395.0,
"medBeginDate": null
}
The javascript file (app.js) contains the following code.
I have a separate files for the views as shown in the angular code below.
For ease of understanding the question, I have put everything in one snippet below.
var flexTable = angular.module("flexTable", ["ngRoute", "ngTable", "ngResource"]);
flexTable.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/about', {
templateUrl: '../../about.html',
controller: 'tableController'
})
.when('/contact', {
templateUrl: '../../contact.html',
controller: 'tableController'
})
.when('/', {
templateUrl: '../../table.html',
controller: 'tableController'
})
.when('/table', {
templateUrl: '../../table.html',
controller: 'tableController'
})
.otherwise({
redirectTo: '/table'
});
}]);
flexTable.controller('tableController',['$scope', '$resource' ,'ngTableParams', function ($scope, $resource,ngTableParams) {
var data = '';
var api = $resource("/Home/GetData")
$scope.tableParams = new ngTableParams({}, {
getData: function (params) {
var varApiGet = api.get(params.url()).$promise.then(function (data) {
params.total(data.inlineCount);
return data.results;
});
return varApiGet;
}
});
}]);
The html page looks as follows
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link href="../../Assets/css/justified-nav.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link href="../../Assets/css/ng-table.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular-sanitize.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular-resource.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular-route.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular-animate.js"></script>
<script src="../../Assets/js/lib/ng-table.min.js"></script>
<script src="../../Assets/js/app.js"></script>
</head>
<body>
<div class="container" >
<!-- The justified navigation menu is meant for single line per list item.
Multiple lines will require custom code not provided by Bootstrap. -->
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Default</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="jumbotron">
<h1>Instructions stuff!</h1>
<p class="lead">Cras justo odio, dapibus ac facilisis in, egestas eget quam.
Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh,
ut fermentum massa justo sit amet.</p>
<!--<p><a class="btn btn-lg btn-success" href="#" role="button">Get started today</a></p>-->
</div>
<div class="container" ng-controller="tableController">
<div ng-view>
<div class="row">
<table ng-table="tableParams" class="table">
<tr ng-repeat="row in $data track by $index">
<td title="'EncType'">
{{row.EncType}}
</td>
<td title="'ClientAlias'">
{{row.ClientAlias}}
</td>
<td title="'OrgName'">
{{row.OrgName}}
</td>
<td title="'CharacterAlias'">
{{row.CharacterAlias}}
</td>
<td title="'AddressCity'">
{{row.AddressCity}}
</td>
<td title="'St'">
{{row.St}}
</td>
<td title="'ZIP'">
{{row.ZIP}}
</td>
<td title="'ContactName'">
{{row.ContactName}}
</td>
<td title="'Fax'">
{{row.Fax}}
</td>
<td title="'PHONE'">
{{row.PHONE}}
</td>
<td title="'CriticalValueNotification'">
{{row.CriticalValueNotification}}
</td>
<td title="'Doctor'">
{{row.Doctor}}
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<footer class="footer">
<p>© 2015 Company, Inc.</p>
</footer>
</div><!--container-->
</body>
</html>
When I have the data hardcoded in the javascript controller function, the table displays fine without the search and sort functionality. When I have the data come in through the ajax call as shown in the code, it displays no data. only the table heading.
I can answer any questions that anyone has about this.
Thanks,
Paras
Any help appreciated.
EDIT
Here is the controller code that worked for me. I also added some extra code for the sorting and the filters.
flexTable.controller('tableController', ['$scope', '$http', 'ngTableParams', '$filter', '$log'
, function ($scope, $http, ngTableParams, $filter, $log) { //
$http.get('/Home/GetData')
.success(function (data, status) {
$scope.data = data;
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
OrganizationName: 'asc' // initial sorting
}
}
, {
total: $scope.data.length, // length of data
getData: function ($defer, params) {
// use build-in angular filter
var filterData = params.filter() ?
$filter('filter')($scope.data, params.filter()) :
$scope.data;
var orderedData = params.sorting() ?
$filter('orderBy')(filterData, params.orderBy()) :
filterData;
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
}
);
});
}]);
You could use $http instead of $resource. Your response data will be in the data property of your response. Try the following:
$scope.tableParams = new ngTableParams({}, {
getData: function(params) {
var varApiGet = $http.get(params.url()).then(function(response) {
var data = response.data;
params.total(data.inlineCount);
return data.results;
});
return varApiGet;
}
});
Edit
Here is a working fiddle. I simulated the response as an array with one entry (the one you posted in the question). Make sure that your response data is in the correct format.

Working with Angular Material

This is a small project just for learning purposes.
The objective is that when I click in the + button in front of the name of the game, the AngularJS material popup show up. Its working, but I want it to work for the different games. With a different HTML template correspondent to the game I click.
Here is my project.
https://github.com/hseleiro/myApp
index.html
<div ng-view>
</div>
assets/js/mainApp.js
var stuffApp = angular.module('myApp', ['ngAnimate','ngRoute','ngMaterial','ui.bootstrap.tpls','ui.bootstrap']);
stuffApp.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/',
{
templateUrl: 'pages/home.html',
controller: 'mainController',
})
.when('/games',
{
templateUrl: 'pages/games.html',
controller: 'mainController'
})
})
stuffApp.controller('mainController', function ($scope,$mdDialog){
$scope.query = {}
$scope.queryBy = '$'
$scope.games = [
{
"name" : "BloodBorne",
"consola" : "Playstation 4"
},
{
"name" : "Mass Efect 3",
"consola" : "Xbox 360"
},
{
"name" : "Pro Evolution Soccer 6",
"consola" : "Xbox 360"
}
];
$scope.showAdvanced = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'pages/dialog1.tmpl.html',
targetEvent: ev,
clickOutsideToClose:true
})
};
function DialogController($scope, $mdDialog) {
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
}
});
pages/games.html
<div class="container">
<div class="row">
<div class="titulo">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<h1><i class="fa fa-gamepad fa-4x"></i></h1>
</div>
<div class="col-sm-4"></div>
</div>
</div>
<div class="row">
<div class="col-sm-1">
<div class="search_icon">
<h4><i class="fa fa-search fa-4x"></i></h4>
</div>
</div>
<div class="col-sm-11">
<div class="search_bar">
<div><input class="form-control" ng-model="query[queryBy]" /></div>
</div>
</div>
</div>
<hr>
<div>
<table class="table">
<tr>
<th>Nome</th>
<th>Consola</th>
</tr>
<tr ng-repeat="game in games | filter:query">
<td>{{game.name}}<md-button class="md-primary" ng-click="showAdvanced($event)">
<i class="fa fa-plus"></i>
</md-button></td>
<td>{{game.consola}}</td>
</tr>
</table>
</div>
</div>
pages/dialog1.tmpl.html
<md-dialog aria-label="">
<form>
<md-dialog-content class="sticky-container">
<md-subheader class="md-sticky-no-effect"></md-subheader>
<div>
<p>
Test
</p>
<img style="margin: auto; max-width: 100%;" alt="Lush mango tree" src="assets/img/bloodborne.jpg">
<p>
Test
</p>
<p>
Test
</p>
</div>
</md-dialog-content>
<div class="md-actions" layout="row">
<span flex></span>
<md-button ng-click="answer('useful')" class="md-primary">
Close
</md-button>
</div>
</form>
</md-dialog>
Could some one help me ? Thanks
Sounds like you need to parameterize the controller and template you pass to $mdDialog.
For example:
$scope.showAdvanced = function(ev, popupIdentifier) {
$mdDialog.show({
controller: popupIdentifier + 'Controller',
templateUrl: 'pages/' + popupIdentifier + '.tmpl.html',
targetEvent: ev,
clickOutsideToClose:true
})
};
and then simply call the function with whatever popup content you need:
$scope.showAdvanced($event, 'Game1');

Why my router UI in angular.js is not working as expected?

my problem is that the routing is not working as expected, here is my code :
$urlRouterProvider.
otherwise('/list');
$stateProvider.
state('home', {
abstract: true,
views: {
'header': {
templateUrl: 'partials/header.html',
controller: 'HeaderController'
},
'breadcrumb': {
templateUrl: 'partials/breadcrumb.html',
controller: function($scope) {
$scope.breadcrumb = ['Home', 'Library', 'Data'];
}
},
'sidebar': {
templateUrl: 'partials/sidebar.html'
}
}
}).
state('home.list', {
url: '/list',
views: {
'main#': {
templateUrl: 'partials/list.html',
controller: 'ListController'
}
}
}).
state('home.details', {
url: '/details/:id',
views: {
'main#': {
templateUrl: 'partials/details.html',
controller: 'DetailsController'
}
}
});
in my index i have this :
<div class="container">
<div class="row">
<!-- SideBar -->
<div ui-view="sidebar" class="col-xs-3 sidebar"></div>
<!-- /.SideBar -->
<div class="col-xs-8">
<!-- Breadcrumb -->
<div ui-view="breadcrumb" class="pull-right"></div>
<!-- /.Breadcrumb -->
<!-- Main Content -->
<div ui-view="main"></div>
<!-- /.Main Content -->
</div>
</div>
</div>
the problem is that the first time i enter the app (the otherwise works fine) but when trying to click on a hyperlink with details/id i get this error : Error: Could not resolve 'details' from state 'home.list', i'm a little bit confused right now !!!
You need to use home.details in ui-sref instead of just details.
I have an example working in this Plunkr.
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in persons">
<!-- <td><a ui-sref="details({id: persons.indexOf(person)})">{{person.name}}</a></td> -->
<td><a ui-sref="home.details({id: persons.indexOf(person)})">{{person.name}}</a></td>
<td>{{person.address}}</td>
</tr>
</tbody>
</table>

Categories