html does not have access to object in controller angularjs - 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.

Related

How to load ng-repeat when switching with routes?

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

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'
});
})

UI-Router, I am trying to pass id in the url, but I keep getting nothing

I am trying pass id in the url so that it can be use by other page more specifically the detail page but i keep getting nothing. the url is going to the correct route but the id is not getting passed in. i have no idea what i'm doing wrong.
here my app.js file:
$stateProvider.state('contact', {
url: '/contact',
templateUrl: 'templates/contact.html',
controller: 'mainController'
});
$stateProvider.state('contact.detail', {
url: '/detail/:id',
templateUrl: 'templates/contact.detail.html',
controller: 'detailController'
});
and here is my controller file:
myApp.controller('detailController', ['$scope', '$stateParams',
function ($scope, $stateParams) {
'use strict';
$scope.peoples = $scope.peoples[$stateParams.id];
}]);
and here is my contact file:
<div class="container">
<div class="row">
<div class="col-md-6">
<table class="table table-striped">
<thead>
<th>First name</th>
<th>Last name</th>
<th>Age</th>
</thead>
<tbody>
<tr ng-repeat="person in peoples">
<td><a ui-sref="contact.detail({id: person.id})">{{person.firstname}}</a></td>
<td>{{person.lastname}}</td>
<td>{{person.age}}</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-6">
<div ui-view></div>
</div>
</div>
There is a working example
One thing is:
searching with indexer, e.g. $scope.peoples[someIdValue] will not find by ID but by position (index)
The second point would be:
do not re-assign a reference $scope.peoples with new value (and lose that reference)
So, this should be the fix (using lodash to find person)
.controller('detailController', ['$scope', '$stateParams',
function($scope, $stateParams) {
//$scope.peoples = $scope.peoples[$stateParams.id];
$scope.person = _.find($scope.peoples, {id: $stateParams.id});
}])
Check that all in action here

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