add menu item value as a class to ng-view - angularjs

I display a list of players as follows, but I'd like to add the name of the player as a class to the ng-view element when the user clicks on a player's name, to view their details via a route. How could I do this?
<tr ng-repeat="player in playersList">
<td>
<a href="#/details/{{player.id)}}">
{{player.name}}
</a>
</td>
View:
<div class="" ng-view></div>
Contoller:
.controller('playersController', function($scope, footballdataAPIservice) {
$scope.playersList = [];
footballdataAPIservice.getPlayers().success(function (response) {
//Dig into the response to get the relevant data
$scope.playersList = response;
});

I'm assuming in the controller for that route you can access the players name?
Just place a data-binding on the ng-view for it's class. Also, within your controller for players, add a value to $rootScope for player name.
<div class="{{ playerName }}" ng-view />
Your controller:
$rootScope.playerName = player.name;

Related

AngularJS: Empty value when access in view

I'm newbie in AngularJS, I have a question, please explain to me the reason of my mistake. At first, I have a factory name CategoryParent with this function declared like this,
routerApp.factory('CategoryParent', function($http) {
var categoryParentFactory = {};
var hostCMSAPI="http://***.***.***.***:****";
// get all categories
categoryParentFactory.allCategoryParents = function() {
console.log("call get allCategoryParents");
return $http.get(hostCMSAPI+'/api/categoryparents/');
};
.......
and a controller call this function named categoryParentController:
.controller('categoryParentController', function(CategoryParent,$scope) {
console.log("cateParent ctrl");
$scope.processing=true;
$scope.dataList=[];
$scope.getAllCategoryParents=function(){
CategoryParent.allCategoryParents().success(function(response){
$scope.processing = false;
$scope.list=response;
});
I'm using ui.router like this (nested view):
.state('home.cateParentMenu',{
url:'/cateParentMenu',
templateUrl:'categoryParentTop.html',
controller:'categoryParentController',
controllerAs:'categoryParent'
})
Parent view trigger controller function here:
The Homey Page
This page demonstrates nested views.
<a ui-sref=".list" class="btn btn-primary">List</a>
<a ui-sref=".paragraph" class="btn btn-danger">Paragraph</a>
<a ui-sref=".cateParentMenu" class="btn btn-warning" ng-click="getAllCategoryParents()">cateParentMenu</a>
and last, the children view come here
data show
{{processing}}
{{list}}
{{item.cate_parent_name}}
<ul class="nav navbar-nav" >
data show
{{processing}}
{{list}}
<li data-ng-repeat="item in list.data"><a ui-sref=".detail({cate_parent_id:item.cate_parent_id})" ng-click="getById(item.cate_parent_id)" ui-sref-active="active" id="{{item.cate_parent_id}}">{{item.cate_parent_name}}</a></li>
</ul>
<div class="col-sm-6">
<div ui-view=""></div>
<!--<div ui-view="serviceRef"></div>-->
<!--<div ui-view="categoryRef"></div>-->
</div>
I set $scope.list and $scope.processing to transfer result to view. But in view I show {{list}}, nothing appears and {{processing}} = true ???
Why? please help me, many thanks to all your suggests.
Controller
Fix $scope.dataList=[]; to $scope.list=[];

Can't access the variable from newly created filter variable of ng-repeat in angular

I have a ng-repeat like this :
<a class="item item-avatar" ng-click="loadProfile({{student.pi_id}})"
ng-repeat="student in filteredStudents = (students | filter:model.txtSearch)" >
<img src="./img/man.png">
<h2>{{student.pi_name}}</h2>
<p>{{student.pi_hp}}</p>
</a>
the question is how can I access the filteredStudents variable? as I can't access it by using $scope.filteredStudents; in the controller
When you are applying the filter in view the filtered value is not accessible in controller.
If you need the filtered data in your controller you need to do filtering in your controller like:
$scope.filteredData = $filter('filter')($scope.filteredStudents, $scope.model.txtSearch)
Inject filter in your controller
function YourController($scope, $filter)
{
}
then, use the filter in controller itself
$scope.filteredStudents = $filter('yourFilterName')(model.txtSearch);
then in html,
<a class="item item-avatar" ng-click="loadProfile({{student.pi_id}})" ng-repeat="student in filteredStudents" >...</a>
Check this SO question
Controllers execute before the view is rendered, which is why the controller function $scope is empty when it executes. You could access the $scope.filteredStudents from within an event handler, such as ngClick:
var app = angular.module('app',[]);
app.controller('ctrl', function($scope) {
$scope.test = function() {
alert ($scope.items);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="name" /> {{name}}
<div ng-repeat="i in items = ([1,2,3,4] | filter:name )">
{{i}}
</div>
<button ng-click="test()">Hey</button>
</div>
Alternatively, you can access $scope.filteredStudents by using $timeout:
app.controller('ctrl', function($scope,$timeout) {
$timeout(function() {
// $scope.filteredStudents is accessible here...
alert($scope.filteredStudents);
});
});
This works because the $timeout hander executes after the view is rendered. The javascript enclosure allows the $timeout handler to execute, and still access the controller's function context.

How to add class to current item in Angular JS?

I have HTML code is formatted via ng-repeat:
<div id="list">
<div class="item" ng-click="Select()"></div>
<div class="item" ng-click="Select()"></div>
<div class="item" ng-click="Select()"></div>
</div>
How I can add class to current .item where was called method Select() after response AJAX?
Angular JS:
$scope.function = Select() {
Ajax () {
response (){
// Here add CSS class to clicked element .item
}
}
}
You will need to do: $scope.select= function() {. Your ng-click is fine.
Manipulating DOM from controller is bad practice & you shouldn't do that wherever you had directive like ng-class
Basically you need to use ng-class directive & selected property in each item to have a track of selected items.
Markup
<div class="item" ng-class="{selected: item.selected}" ng-repeat="item in items"></div>
Controller
$scope.Select = function(item) {
$http.get('url').success(function(){
item.selected = true;
})
}

angularjs static searchbox in all pages

I have a searchbox , list of items , when I click on each item it will take me to the item info tempate.
right now in my below code the searchbox is inside the items.html and it only appears in there meaning it does not appear when i am on the intem.html template viewing the info .
Can you assist me in keeping my searchbox view-able in all pages and outside the ng-view? and yet the items list will not appear when I am viewing an item info but the searchbox appears . but when I search , the ng-view will show the search results in this ng-view instead of the item info ?
This is the current code :
items.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/items', {
templateUrl: 'items.html',
controller: 'ItemsController',
//some API code happens here to get the search results list
}
})
.when('/items/:id', {
templateUrl: 'item.html',
controller: 'ItemController',
//some API code happens here to get the info
}
}
})
.otherwise({
redirectTo: '/items'
});
<div class="container">
<hr>
<div ng-view></div>
</div>
<!--items.html-->
<input class="form-control" type="text" placeholder="Search ..." ng-model="search" >
<table>
<tr ng-repeat="item in items | filter:search">
<td><a ng-href="#/items/{{item.id}}" ></a>
<td> {{ item.title }}</td>
</tr>
</table>
<!-- item.html>

angularjs ng-repeat list not updated when element is added/removed

There is a list of users retrieved from a rest api. Here is the template
<div ng:controller="UserController">
<a ng-click="createUser()">Create User</a>
<div ng-view>
<ul>
<li ng-repeat="user in users">
{[{user.first_name}]} {[{user.last_name}]}
</li>
</ul>
</div>
</div>
The JS:
function UserController($scope, User, Group){
$scope.users = User.query();
$scope.createUser = function(){
//$scope.users = null;
//$scope.users.pop();
//$scope.users.push(new User({id:'5'}));
console.log($scope.users);
}
}
The service: http://dpaste.com/1065440/
All users a retrieved and listed correctly. The problem is that I cannot manipulate the rendered list at all. No matter what I do push, pop or set to null. The list does not change in the template. However the last log statement shows the changes, it prints e.g. NULL when the users array is set to null.
Any ideas where the problem is?
The object you push into the array should be an instance of User
function UserController($scope, User){
$scope.users = User.query();
$scope.createUser = function(){
$scope.users.push(new User({first_name:'Bob', last_name: 'Schmitt'}));
}
}
So, use new User({})
From our conversation, it seems the problem was in the routing. The same outer controller was assigned to the partial that was being loaded in the ng-view. Removing ng:controller="UserController" and moving the createUser button to the partial would solve the problem, but if there's really a need to call the createUser method from outside of ng-view, then all the data related to it will need to be in the outer controller. So, you can keep your outer controller as it is, and change your route to use an empty placeholder controller.
make sure createUser is being called. IE ng-click or something.
<button type="button" ng-click="createUser()">Create User</button>
Your push function looks correct, but your binding in html looks wrong. It should be double curly brackets.
<li ng-repeat="user in users">
{{user.first_name}} {{user.last_name}}
</li>
Added Example I've used previously on adding object.
<div ng-app="main">
<div ng-controller="MyCtrl">
<button ng-click="add()" >Add</button>
<div id="container">
<div ng-repeat="test in tests>{{test.name}}</div>
</div>
</div>
</div>
$scope.tests = {};
$scope.add = function() {
var newTest = {name: 'Test Message'};
$scope.tests.push(newTest);
};

Resources