If I had some code similar to this, how would I go about calling the getUserName() function inside the ng-repeat. I attempted to do it earlier and it worked, however, it no longer functions.
var user_reviews = [{
user: {
name: "John Doe"
},
review: {
item: "Shure SE215"
}
}]
var app = angular.module("ExApp", []);
app.controller("TestController", function($scope) {
$scope.reviews = user_reviews;
$scope.getUserName = function() {
return $scope.user.name;
}
});
HTML
<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{review.getUserName()}}</p>
</div>
</div>
You can pass the index from ng-repeat and return the user.name relevant to that index
<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{getUserName($index)}}</p>
</div>
</div>
var app = angular.module("ExApp", []);
app.controller("TestController", function($scope){
$scope.reviews = user_reviews;
$scope.getUserName = function(index){
return $scope.reviews[index].user.name;
}
});
but if you are using function for this senario only i prefer do it without the function like this
<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{review.user.name}}</p>
</div>
</div>
Assuming scope.getUserName() isn't as trivial as it is in your example, you can do this instead.
// Pass the `review` object as argument
$scope.getUserName = function(review){
return review.user.name; // get the user name from it
}
HTML, pass review as parameter
<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{getUserName(review)}}</p>
</div>
</div>
//You can directly access the username
<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{review.user.name}}</p>
</div>
</div>
//or You can pass the review as parameter and return username from that function.
//HTML
<div ng-controller="TestController">
<div ng-repeat="review in reviews">
<p>{{getUserName(review)}}</p>
</div>
</div>
//JS
$scope.getUserName = function(review){
return review.user.name;
}
You should change your code to this.
<div ng-controller="TestController"><div ng-repeat="review in reviews">
<p ng-repeat="userName in review.getUserName(review.name)">{{userName.name}}</p></div></div>
var user_reviews = [
{
user:{
name: "John Doe"
},
review:{
item: "Shure SE215"
}
}
]
var app = angular.module("ExApp", []);
app.controller("TestController", function($scope){
$scope.reviews = user_reviews;
$scope.getUserName = function(userName){
return $scope.user.name;
}
});
Related
I'm new in AngularJS, I want to create an array and post it to server by register function, here's Controller code:
root.controller('mainController', function($scope) {
$scope.lineItems = [];
$scope.addItem = function (id) {
$scope.lineItems.push(id);
console.log($scope.lineItems);
// gives me right data -> Array [ "1", "2", "3", "4", "1" ]
};
$scope.register = function () {
// post data to server
console.log($scope.lineItems);
// gives me an empty array -> Array [ ]
};
});
Here's HTML code and directives:
<div class="container" ng-controller="mainController">
<a ng-click="register()"></a>
<div ng-repeat="product in products">
<a class="btn" ng-click="addItem(product.id)">Add</a>
</div>
</div>
The problem occurs when i want to call register function, it gives me an empty array instead of array elements while it's not gonna happen in addItem function.
This is your code and work correctly.
var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
$scope.products = [{id:1},{id:2},{id:3},{id:4}];
$scope.lineItems = [];
$scope.addItem = function (id) {
$scope.lineItems.push(id);
console.log($scope.lineItems);
// gives me right data
};
$scope.register = function () {
// post data to server
console.log($scope.lineItems);
// gives me an empty array
};
});
<div ng-app="testApp" ng-controller="testCtrl">
<a ng-click="register()">Register</a>
<div ng-repeat="product in products">
<a class="btn" ng-click="addItem(product.id)">Add : {{product.id}}</a>
</div>
</div>
I'm creating a small event app with angular for practicing. Currently i've created a application with Laravel 5.1 and returning some URL's with JSON. I load those URL's in my Factory for the events. Those events will be rendered with Angular. After they are rendered, a button with "Show info" will be placed and when you click at it, i want to call a function in the EventController so my $scope.event will receive the new data. My Controller has a function with $scope.getEvent(eventID); but i cant figure out how to run that function on click.
//Controller
app.controller('EventController', ['$scope', 'eventFactory', '$http', function ( $scope, eventFactory, $http )
{
eventFactory.getEvents(1).then(function(response){
$scope.events = response.events;
$scope.eventPaginator = response.pagination;
});
$scope.getEvent = function(value){
console.log('trigger');
eventFactory.getEvent(value).then(function(response){
$scope.event = response;
});
};
$scope.loadPage = function(page){
eventFactory.getEvents(page).then(function(response){
$scope.events = response.events;
$scope.eventPaginator = response.pagination;
});
};
}]);
//Directive
app.directive('event', function() {
return {
restrict: 'E',
scope: {
data: '=',
loadEvent: '&',
},
templateUrl: '/assets/website/angular/views/event.html',
link: function(scope, element){
scope.loadEvent(function(){
alert('Click')
});
},
};
});
//Factory
app.factory('eventFactory', ['$http', function ( $http )
{
return {
getEvents: function (page)
{
return $http.get('/api/v1/events?page='+page)
.then(function ( response )
{
return response.data;
});
},
getEvent: function (id)
{
return $http.get('/api/v1/event/'+id)
.then(function ( response )
{
return response.data;
});
}
};
}]);
//View
<div class="event">
<h2>[[data.event.title]] ID: [[data.event.id]]</h2>
<div class="event-image">
</div>
<div ng-click="loadEvent(data.event.id)">Click voor [[data.event.id]]</div>
</div>
//HTML code for the Laravel View
<div class="col-md-9" ng-controller="EventController">
<div class="btn btn-success" ng-click="getEvent(15)">Test</div>
<div class="row">
<h1 ng-bind="showEvent.event.title"></h1>
{#<div class="col-md-12">#}
{#<h1 class="page-header">Page Heading <small>Secondary Text</small></h1>#}
{#<div ng-controller="BannerController">#}
{#<ul rn-carousel rn-carousel-auto-slide="3" rn-carousel-transition="slide" rn-carousel-duration="1000" class="image carousel">#}
{#<li ng-repeat="banner in banners">#}
{#<img ng-src="[[banner.image]]" alt="" class="img-responsive">#}
{#</li>#}
{#</ul>#}
{#</div>#}
{#</div>#}
<div class="col-sm-12">
<div class="row">
<div class="col-sm-4" ng-repeat="event in events">
<h1>Een event</h1>
<event data="event"></event>
</div>
</div>
</div>
<div class="col-sm-12">
<h3>[[eventPaginator.total]]</h3>
<div class="pagination">
<div ng-repeat="n in [] | range:eventPaginator.total">
<button ng-click="loadPage(n+1)">[[n+1]]</button>
</div>
</div>
</div>
</div>
</div>
I think you wanted to call the parent controller function from the directive template with passing id parameter to it. For that you need to pass the method reference to the directive in by adding load-event attribute with getEvent(id) on the directive element.
Also you should remove the unwanted link which has wrong code in it.
//below code should remove from the directive.
scope.loadEvent(function(){
alert('Click')
});
Directive Template
<event data="event" load-event="getEvent(id)"></event>
Template
<div ng-click="loadEvent({id: data.event.id})">Click voor [[data.event.id]]</div>
I try to build new APP with ionic framework and Angularjs.
Now my problem is i cannot show the result from controller to view. I try open console.log(allposts); in my browser ans we show the result good.
But in view its not show any thing
allpost.html
<dive class="item itemfull" ng-repeat="post in allpost">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news"><div class="title" ng-bind-html="post.content"></div></div>
</div>
</div>
</div>
And the controller
myApp.controller('allpost', function($scope , $http , $stateParams , Allposts) {
var id = $stateParams.id;
$scope.post = Allposts.GetAllposts(id);
});
myApp.factory('Allposts',['$http', '$q',function($http,$q){
var allposts = [];
var pages = null;
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id="+id+"&status=publish",{params: null}).then(function (response) {
items = response.data.posts;
allposts = items;
console.log(allposts);
return items;
$ionicLoading.hide();
});
}
}
}]);
Where is error ?
try to change the code like this in controller and factory in js files
.controller('allpost', function ($scope, $http, $stateParams, Allposts) {
var id = $stateParams.id;
Allposts.GetAllposts(id).then(
function (response) {
$scope.allPosts = response.data.posts;
});
})
.factory('Allposts', ['$http', '$q', function ($http, $q) {
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id=" +
id + "&status=publish");
}
}
}]);
the html file
<div class="item itemfull" ng-repeat="post in allPosts">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news">
<div class="title" ng-bind-html="post.content"></div>
</div>
</div>
</div>
</div>
It works for my test
I have the following thing on my Angular app:
$scope.things = [{
title: 'Simple',
type: 1,
form: {
input: [1, 2, 3],
clone: true
}
}];
$scope.clone = function(item) {
item.form.input.push(Math.floor(Math.random() * 999));
};
And on the HTML part:
<div ng-repeat="item in things" class="item">
<h2>{{item.title}}</h2>
<div ng-repeat="input in item.form.input">
<input type="text" />
</div>
<button ng-click="cloneInput(item)">Clone</button>
</div>
When press the Clone button I'm pushing a new element to form.input array and add a new input to the DOM.
I want to $http.post all the values for the inputs.
I know to push something I need to use
$http.post('/path/to/my/api', {my object}).callback()
But I dont know how to make an object from all the .item inputs.
Can someone explain me how or suggest a better solution?
If you use a ng-model for your inputs and set it to an object you can then inject that object to the post, here is a really basic example:
JSFiddle
HTML:
<div ng-app="myApp" ng-controller="dummy">
<div ng-repeat="input in items">
<input type="text" name="{{input.name}}" ng-model="data[input.name]" />
</div>
<button ng-click="submit()">Submit</button>
<p ng-show="displayIt">{{data}}</p>
</div>
JS:
angular.module('myApp', [])
.controller('dummy', ['$scope', function ($scope) {
$scope.items = [{
name: 'test'
}, {
name: 'test2'
}];
$scope.data = {};
$scope.displayIt = false;
$scope.submit = function () {
// This is only to check it
$scope.displayIt = true;
// Do your post here
};
}]);
I am trying to create a page where you have few items in a list group which when selected should show more details.
Please view the example here http://plnkr.co/edit/Oava3pA9OTsm80K58GdT?p=preview
How can I populate the details from the json file based on the item that is selected in the list group?
This is what I have so far.
html:
<div ng-controller=ItemsController>
<h3>Test</h3>
<div class="row">
<div class="col-md-4">
<div class="panel panel-default">
<ul class="list-group">
<a class="list-group-item" ng-repeat="item in itemDetails">{{item.name}}</a>
</ul>
</div>
</div>
<div class="col-md-8">
<div class="panel panel-default">
<h2>Name: </h2>
<br />Address Line 1:
<br />Address Line 2:
<br />Suburb:
<br />Phone:
<br />Email:
</div>
</div>
</div>
</div>
script:
var myItemsApp = angular.module('myItemsApp', []);
myItemsApp.factory('itemsFactory', ['$http', function($http){
var itemsFactory ={
itemDetails: function() {
return $http(
{
url: "mockItems.json",
method: "GET",
})
.then(function (response) {
return response.data;
});
}
};
return itemsFactory;
}]);
myItemsApp.controller('ItemsController', ['$scope', 'itemsFactory', function($scope, itemsFactory){
var promise = itemsFactory.itemDetails();
promise.then(function (data) {
$scope.itemDetails = data;
console.log(data);
});
}]);
json:
[
{
"$id":"1",
"name":"Test itemName 1",
"themeName":"ASD",
"addressLine1":"18 Banksia Street",
"addressLine2":null,
"suburb":"Heidelberg",
"state":"VIC",
"postalCode":"3084",
"contactPhone":"+61 3 123456",
"emailAddress":"qwerty.it#xyz.com"
},
{
"$id":"2",
"name":"Test itemName 2",
"themeName":"WER",
"addressLine1":"11 Riverview Place",
"addressLine2":"Metroplex on Gateway",
"suburb":"Murarrie",
"state":"QLD",
"postalCode":"4172",
"contactPhone":"1300 73123456",
"emailAddress":"asdfg.it#xyz.com"
},
{
"$id":"3",
"name":"Test itemName 3",
"themeName":"ERT",
"addressLine1":"60 Waterloo Road",
"addressLine2":null,
"suburb":"North Ryde",
"state":"NSW",
"postalCode":"2113",
"contactPhone":"123456",
"emailAddress":"zxcvb.it#xyz.com"
}
]
Any help would be greatly appreciated.
I am very new to programming. Please also feel free to alternative ways of achieving this if I have done it wrong.
You can use the ng-click directive to specify what happens when you click something.
So I made it assign the clicked item to the $scope.selected object using a function ($scope.select(item)) and then I bound the properties of that object to your little details section. That's probably the simplest way to do it.
Ctrl
$scope.select = function(item) {
$scope.selected = item;
}
$scope.selected = {};
HTML
<a class="list-group-item" ng-click="select(item)" ng-repeat="item in itemDetails">
{{item.name}}
</a>
And the selected object is then available like this:
<h2>Name: {{selected.name}}</h2>
etc...
See my example here: http://plnkr.co/edit/mUMZ0VGO8l1ufV1JJNQE?p=preview