How to load ng-repeat when switching with routes? - angularjs

I want to load the data from the api when i click the route instead of the button i have atm.
i tried calling the function with ng-click on the index.html but it didnt work.
routes:
import { app } from "../index";
app.config(function($routeProvider, $locationProvider) {
$locationProvider.hashPrefix("!");
$routeProvider
.when("/drivers", {
templateUrl: "./src/pageDetails/drivers.html",
})
.when("/teams", {
templateUrl: "./src/pageDetails/teams.html",
})
.when("/races", {
templateUrl: "./src/pageDetails/races.html",
});
});
app controller:
import {app} from '../index';
app.controller("api", function($scope, $http) {
$scope.Naziv = "Driver Championship Standings - 2013";
$scope.TopDrivers = function () {
console.log("i been pressed");
$http.get("https://ergast.com/api/f1/2013/driverStandings.json")
.then(function successCallback(response) {
$scope.drivers = response.data.MRData.StandingsTable.StandingsLists[0].DriverStandings;
console.log("response.data.MRData.StandingsTable.StandingsLists.0.DriverStandings");
console.log(response.data.MRData.StandingsTable.StandingsLists[0].DriverStandings);
}, function errorCallback(response) {
console.log("Unable to perform get request");
});
}
});
my ng-repeat
<div ng-controller="api">
<p>{{Naziv}}</p>
<button ng-click="TopDrivers()">Test Rest</button>
<div ng-repeat="x in drivers | orderBy: '+Points'">
<div id="divRow">
<table>
<tr id="tableRow">
<td id="td1">Nb: {{x.position}}</td>
<td id="td2">
{{x.Constructors[0].nationality}} {{x.Driver.givenName}} {{x.Driver.familyName}}
</td>
<td id="td3">{{x.Constructors[0].name}}</td>
<td id="td4">Points{{x.points}}</td>
</tr>
</table>
</div>
</div>
</div>
index.html how the route is called
<p class="leftText" id="firstPLEft">
<img class="leftPictures" src="img/drivers.png" alt="DriversPng">
Drivers
</p>
i want to load the api and have it give me the ng-repeat results when i switch to the route instead of when i click the button in the route.

How about using ng-init
<div ng-controller="api" ng-init="TopDrivers()">
<p>{{Naziv}}</p>
<buttonTest Rest</button>
<div ng-repeat="x in drivers | orderBy: '+Points'">
<div id="divRow">
<table>
<tr id="tableRow">
<td id="td1">Nb: {{x.position}}</td>
<td id="td2">
{{x.Constructors[0].nationality}} {{x.Driver.givenName}} {{x.Driver.familyName}}
</td>
<td id="td3">{{x.Constructors[0].name}}</td>
<td id="td4">Points{{x.points}}</td>
</tr>
</table>
</div>
</div>
</div>
Or, you can use resolve in $routeProvider:
app.factory("someService", function($http){
return {
getData: function(){
return $http.get("https://ergast.com/api/f1/2013/driverStandings.json");
}
};
});
and in config:
$routeProvider
.when("/drivers", {
templateUrl: "./src/pageDetails/drivers.html",
controller: "api",
resolve: {
message: function(someService){
return messageService.getData();
}
})
.when("/teams", {
templateUrl: "./src/pageDetails/teams.html",
})
.when("/races", {
templateUrl: "./src/pageDetails/races.html",
});
A sample demo on how to use it

Related

ng-app and ngRoute not working

I have the following script.js code
var app = angular
.module("Demo", ["ngRoute"])
.config(function ($routeProvider) {
$routeProvider
.when("/home", {
templateUrl: "Templates/home.html",
controller: "homeController"
})
.when("/courses", {
templateUrl: "Templates/courses.html",
controller: "coursesController"
})
.when("/students", {
templateUrl: "Templates/students.html",
controller: "studentsController"
})
})
.controller("homeController", function ($scope) {
$scope.message = "Home Page";
})
.controller("coursesController", function ($scope) {
$scope.courses = ["C#", "VB.NET", "ASP.NET", "SQL Server"];
})
.controller("studentsController", function ($scope, $http) {
$http.get("StudentService.asmx/GetAllStudents")
.then(function (response) {
$scope.students = response.data;
})
})
and the following is the html :
<body ng-app="Demo">
<table style="font-family: Arial">
<tr>
<td colspan="2" class="header">
<h1>
WebSite Header
</h1>
</td>
</tr>
<tr>
<td class="leftMenu">
Home
Courses
Students
</td>
<td class="mainContent">
<ng-view></ng-view>
</td>
</tr>
<tr>
<td colspan="2" class="footer">
<b>Website Footer</b>
</td>
</tr>
</table>
The routing does not work for the above href links. My partial pages consumes the properties of $Scope in the script.js file. But home.html never get loaded after clicking the link. Please help with why ng-app, ng-view, and ngRoute do not work for me.
Drop the hashes in your <a> tags.
it works now since I updated the code as following:
var app = angular.module('Demo', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$locationProvider.hashPrefix('');//this helped fix a bug with angular 1.6.1 http://stackoverflow.com/questions/41211875/angularjs-1-6-0-latest-now-routes-not-working the routing links were not working but this $locationProvider variable change fixed it.
$routeProvider
.when('/home', {
templateUrl: 'Templates/home.html',
controller: 'homeController'
})
.when('/courses', {
templateUrl: 'Templates/courses.html',
controller: 'coursesController'
})
.when('/students', {
templateUrl: 'Templates/students.html',
controller: 'studentsController'
});
})

html does not have access to object in controller angularjs

I want to show the object in view. The object itself is the controller, but the html does not have access to its properties (probably not see the model)! Maybe the problem ui routing?
app.js
(function () {
'use strict';
angular
.module('hawk', [
'ngWebsocket',
'ui.bootstrap',
'ui.router',
'hawk.controllers',
'hawk.services',
'hawk.directives'
])
.config(['$stateProvider', '$urlRouterProvider', router])
.run(['$rootScope', main]);
angular.module('hawk.services', []);
angular.module('hawk.directives', []);
angular.module('hawk.controllers', []);
function router($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/list');
// CARDS OBJECT VIEW
$stateProvider
.state('list', {
abstract: true,
url: '/list',
templateUrl: '/app/app-eng/controllers/list.html',
controller: 'ListController as dc'
})
.state('list.cards-list', {
url: '/cards-list',
templateUrl: '/app/app-eng/controllers/object-card/cards-list.html',
controller: 'CardsListController as dc',
})
.state('list.contract', {
url: '/contract',
templateUrl: '/app/app-eng/controllers/object-card/contract.html',
controller: 'ContractController as dc',
})
}
function main ($rootScope) {
$rootScope.object = {};
}
})();
The submittion list.cards-list I have access to the object (from model), but submitting list.contract I get the object and can not access its properties (in model). Why?
list.html
<div class="list-group col-md-2 sidebar-offcanvas">
<uib-tabset active="activePill" vertical="true" type="pills">
<uib-tab index="0" heading="Cards list" ui-sref="list.cards-list"></uib-tab>
<uib-tab index="1" heading="Contract" ui-sref="list.contract"></uib-tab>
</uib-tabset>
</div>
<div class="col-md-10">
<div ui-view></div>
</div>
contract.html
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Contract #{{ 2222222}}</h3>
</div>
<table class="table table-condensed">
<tr>
<td width="10%" align="right"><strong>№ contract:</strong></td>
<td>{{dc.data.id}}</td>
</tr>
<tr>
<td align="right"><strong>Date start:</strong></td>
<td>{{dc.data.cdstart}}</td>
</tr>
<tr>
<td align="right"><strong>Date end:</strong></td>
<td>{{dc.data.cdend}}</td>
</tr>
<tr>
<td align="right"><strong>Type name:</strong></td>
<td>{{dc.data.tyonames}}</td>
</tr>
<tr>
<td align="right"><strong>Category.:</strong></td>
<td>{{dc.data.ccategory}}</td>
</tr>
<tr>
<td align="right"><strong>Police department:</strong></td>
<td>{{dc.data.rpnames}}</td>
</tr>
</table>
</div>
contract.js
(function() {
'use strict';
angular
.module('hawk.controllers')
.controller('ContractController', ContractController);
ContractController.$inject = ['$scope', 'Websocket'];
function ContractController ($scope, Websocket) {
var vm = this;
vm.data = {};
init();
function getContracts (id) {
console.log('getContracts-id', id);
Websocket.getContracts({ id: id }).then(function(data) {
console.log('getContracts-data', data);
vm.data = data.data;
console.log('getContracts-vm.data', vm.data);
});
}
function getAddress (id) {
Websocket.getAddress({ id: id }).then(function(data) {
console.log('getAddress', data);
vm.address = data.data;
});
}
function init () {
$scope.$watch('object.id', function(newValue, oldValue) {
console.log('cc', newValue, oldValue, $scope.object.id);
getContracts($scope.object.id);
});
}
}
})();
you have to access your variables with the "vm." inside your html -> "{{vm.data}}" etc.
//EDIT:
If you want to access them without the "vm" you have to put your variables into the "$scope" in your controller.

AngularJS state change using ui-router causing flickering on UI

I have a very simple two page app and when navigating from listing page to details page, there is a very distinct flicker caused due to hide/show of the UI components. Attached is a screenshot where you can see both UIs visible at the time of transition (at the top is the details UI and at the bottom is the list UI)!
I am using ui-router for navigation.
function routingConfig($stateProvider, $urlRouterProvider, $locationProvider, applicationPathProvider) {
$stateProvider
.state('activities', {
url: applicationPathProvider.getBase(),
views: {
'': {
templateUrl: '/js/activity/activityList.partial.html',
controller: 'ActivityListController',
controllerAs: 'activityListController',
resolve: {
activitiesResponse: function(activityListService) {
return activityListService.listActivities();
}
},
ncyBreadcrumb: {
parent: '',
label: 'Activity List'
}
}
}
})
.state('activityDetails', {
url : applicationPathProvider.getPath('activityDetails'),
templateUrl : '/js/activity/activityDetails/activityDetails.partial.html',
controller : 'ActivityDetailsController',
controllerAs: 'activityDetailsController',
resolve: {
activityDetailsResponse: function($state, $stateParams, activityListService) {
return activityListService.getTasksForActivity($stateParams.activityId);
}
},
ncyBreadcrumb: {
parent: 'activities',
label : '{{activityDetailsController.selectedActivityText}}'
}
})
;
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise(applicationPathProvider.getBase());
}
Here is the service code which sends a REST call and creates a data structure which controller uses.
function getTasksForActivity(activityId) {
var deferred = $q.defer();
Restangular.one("activities", activityId).customGET("tasks")
.then(function (restangularTasks) {
deferred.resolve(buildValidTasksResponse(restangularTasks.plain()));
}, buildErrorTasksResponse);
return deferred.promise;
}
Here is the code for page 1 (the list page)
<div class="sl-artefact-plans" layout="row" flex>
<div class="sl-artefact-list-container" layout="column" style="width: 100%">
<div class='list_table'>
<div class='list_row' ng-repeat="activity in activityListController.activities | orderBy:sortType:sortReverse">
<div class='list_cell overflow td'>
<a ui-sref="activityDetails({activityId: activity.id})"
ng-click="activityListController.setSelectedActivityInService(activity)">
{{activity.summary}}
</a>
</div>
<div class='list_cell td' ng-bind="activity.dueBy | date:'MM/dd/yyyy h:mm a' : 'UTC'">
</div>
<div class='list_cell td' ng-bind="activity.status">
</div>
</div>
</div>
</div>
</div>
And this is page 2:
<div class="sl_artifact_details_header_bar">
<div class="sl_artifact_details_heading">
{{activityDetailsController.selectedActivityText}}
</div>
<div class="sl_artifact_details_info">
<span ng-class="activityDetailsController.selectedActivityStatus"
style="vertical-align:middle; margin:0px 0px 0px -3px">
{{activityDetailsController.selectedActivity.dueBy | date:'MM/dd/yyyy h:mm a' : 'UTC'}}</span>
<span style="padding-left: 10px">{{activityDetailsController.selectedActivity.status}}</span>
</div>
</div>
<table>
<tr ng-repeat="task in activityDetailsController.tasks">
<td ng-bind="task.summary"></td>
<td ng-bind="task.status"></td>
<td ng-bind="task.dueBy"></td>
</tr>
</table>
This is a very simple use-case and I am quite confused as to why is this occurring and how to resolve this.
Any pointers will help. Thanks.

Angular trouble with $http.get

I just started learning Angular and I am having trouble retrieving data based on a http-get request. It works when I simply retrieve all movies, but not when I try to retrieve movies based on a search term (cfr. search.html). I hope someone can tell me where I went wrong, I really can't see it. Thank you in advance.
app.js:
var app;
(function() {
app = angular.module('imdb', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/search', {
controller: 'SearchController',
templateUrl: 'views/search.html'
})
.when('/movies', {
controller: 'MovieController',
templateUrl: 'views/movies.html' //works fine
})
.otherwise({
redirectTo: '/movies'
});
});
})();
SearchController.js
(function (app) {
app.controller('SearchController', ['$http', '$scope', function ($http, $scope) {
$scope.movies = [];
$scope.searchMovie = function(title) {
$http.get('https://angularbackend.azurewebsites.net/api/Movies/Search?title=' + title)
.success(function(data) {
$scope.movies = data;
});
};
}]);
})(app);
search.html
<div>
<form class="form" novalidate name="searchMovies" ng-submit="SearchController.searchMovie(title)" >
<input type="text" ng-model="title" class="form-control" placeholder="enter title">
<button type="submit" class="btn btn-primary btn-block">Search</button>
</form>
<table class="table">
<thead>
<tr>
<th>poster</th>
<th>title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="movie in movies">
<td>{{ movie.title }}</td>
</tr>
</tbody>
</table>
</div>
Replace
SearchController.searchMovie(title)
by
searchMovie(title)
All expressions are always evaluated on the scope. So the first, incorrect one, will try to invoke the method searchMovie of $scope.SearchController, which doesn't exist.
Also note that success() is deprecated for quite some time now. Use then():
$http.get('https://angularbackend.azurewebsites.net/api/Movies/Search?title=' + title)
.then(function(response) {
$scope.movies = response.data;
});
You should also avoid using string concatenation to pass parameters. Those need to be encoded properly. So rather use
$http.get('https://angularbackend.azurewebsites.net/api/Movies/Search', {params: {title: title}})
.then(function(response) {
$scope.movies = response.data;
});

Controller is not a function, got undefined

I'm trying to create a directive on a controller. The directive will create a table of items returned from djangorestframework.
controller.js:
var expensesApp = angular.module('expensesApp', []);
expensesApp.controller('ShoppingListController', ['$scope', '$http',
function($scope, $http){
$http(
{
method: 'GET',
url: '/items/?format=json'
})
.success(function(data, status, headers, config) {
$scope.items = data;
})
.error(function(data, status, headers, config) {
});
}]);
directive.js
angular.module('expensesApp', [])
.directive('shoppingList', function () {
return {
restrict: 'A',
templateUrl: 'http://localhost:8000/static/angular/partials/shopping-list.html',
controller: 'ShoppingListController'
};
})
The partial being pulled in by the directive:
shopping-list.html
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>SHOP</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>[[ item.id ]]</td>
<td>[[ item.name ]]</td>
<td>[[ item.shop ]]</td>
</tr>
</tbody>
</table>
and the main html page where I define the app and the controller.
items.html
...
<div class="container" ng-app="expensesApp">
<div class="row">
<div class="col-md-6" ng-controller="ShoppingListController">
<div shopping-list></div>
</div>
</div>
</div>
...
The headers of the table in the partial are being pulled into the page, but it's not executing the $http and fetching the items that should make up the content of the table. I get ShoppingListController not a function, got undefined
Everything works if I don't split the table out into a directive. All items are returned and I don't see the error in the console.
Anyone have any idea what I'm doing wrong?
You are redefining module when you create a directive. It should be:
angular.module('expensesApp')
.directive('shoppingList', function () {
return {
restrict: 'A',
templateUrl: 'http://localhost:8000/static/angular/partials/shopping-list.html',
controller: 'ShoppingListController'
};
});
If you pass an array as the second argument to module method angular.module('expensesApp', []), Angular creates a new module without ShoppingListController controller in it. You should use getter syntax angular.module('expensesApp') to retrieve previously created module.

Resources