ng-repeat not adding new items dynamically - angularjs

I am new to Angular JS (1) and I am having issues with ng-repeat. I am using socket.io with Angular. Here is my controller:
var messagingApp = angular.module('messagingApp', []);
function mainController($scope) {
var socket = io.connect();
socket.on('message', function(data){
$scope.users.push({'Name': 'yeh'});
console.log($scope.users);
});
$scope.users = []; //if I put stuff here and comment out socket stuff, it shows in the front-end
};
messagingApp.controller('mainController',mainController);
I can see that it is going inside that on block (via console.log). However, it is not displaying anything to the front-end. My front-end is as follows:
<body ng-controller="mainController">
<div ng-repeat="user in users">
<p>{{ user.Name }}</p>
</div>
My understanding is that if you change the model (users in this case), it should automatically update the ng-repeat. Any help would be appreciated.

Add $scope.$apply() after pushing to the array. Because you are updating the model outside of the angular scope. So the angularjs doesnot know the model has been updated. More about $scope.$apply http://tutorials.jenkov.com/angularjs/watch-digest-apply.html

you are pushing the object in array and try to iterate Array. So you should specify the position.
<body ng-controller="mainController">
<div ng-repeat="user in users">
<p>{{ user[$index].Name }}</p>
</div>
or try this..
socket.on('message', function(data){
$scope.users.data.push({'Name': 'yeh'});
console.log($scope.users.data);
});
$scope.users = {data:[]};
<div ng-repeat="user in users.data">
<p>{{ user.Name }}</p>
</div>

Related

AngularJS NG-Repeat JSON

I apologize for this simple question. I've been scouring other questions and still can't get it to work.
I have a function returning some key/value pairs
function(data){
console.log(data.message);
}
Returns...
Object {name: "mpierce486", body: "asfsf", time: "1 second ago"}
I have the following when not logging to console...
$scope.message = data.message
Lastly, here's the markup. I'm using a Laravel app so I'm escaping the {{ with #. Nothing shows up and I know it's a simple mistake. Please assist! Thanks!
<div ng-app="myApp" ng-controller="messageCtrl">
<div ng-repeat="x in message" class="main-user-post">
<h1>#{{ x.body }}</h1>
</div>
</div>
I don't think you can do an ng-repeat on an object. Since it's already an object, not an array, you can access it directly, without ng-repeat.
<div ng-app="myApp" ng-controller="messageCtrl">
<div class="main-user-post">
<h1>#{{ message.body }}</h1>
</div>
</div>
your message variable is an object, not an array. So in your iteration, x will take the value of each object properties (body, name, time).
So either use a different approach, or transform your message to an array:
$scope.message = [data.message];
you can iterate through object properties with angular like this:
<div ng-app="myApp" ng-controller="messageCtrl">
<div ng-repeat="(key, value) in message" class="main-user-post">
<h1>#{{value}}</h1>
</div>
</div>
Create object array as below.
JSFiddle - https://jsfiddle.net/L7k6g7ua/ for reference w.r.t AngularJs -
Hope this helps!
<body ng-app="SampleApp">
<div ng-controller="messageCtrl">
<div ng-repeat="m in message" class="main-user-post">
<h1>{{m.body}}</h1>
</div>
</div>
</body>
var sampleApp = angular.module("SampleApp", []);
sampleApp.controller('messageCtrl', function($scope) {
var myObject = {
name: "mpierce486",
body: "asfsf",
time: "1 second ago"
};
var myArray = [];
myArray.push(myObject);
$scope.message = myArray;
});

Cannot get Angular scope data in Laravel Blade view

I am new to Angular. I am trying to get data from the Angular controller into Laravel Blade. For some reason it is not working.
The socket.io part is working. I did console.log on $scope.message and it is there.
So the problem is between Angular code and Laravel blade. My code is:
<body ng-app="app">
<div ng-controller="AppCtrl">
<input id="auth_id" type="hidden" value="{{ Auth::user()->id }}" />
<h1>New Users</h1>
<ul>
<li ng-repeat="message in messages">
#{{ message.body }}
</li>
</ul>
</div>
<script src="{{ asset('/js/socket.io.js') }}"></script>
<script>
var app = angular.module('app', [])
.controller('AppCtrl', function ($scope){
var socket = io('http://192.168.10.10:3000');
$scope.id = document.getElementById('auth_id').value;
socket.on("user."+ $scope.id + ":App\\Events\\EventDeletedOrEditedBroadcast", function(data) {
$scope.messages = data.message;
});
});
</script>
</body>
Thanks in advance.
the variable you declare in the scope is not the same that wich you want to acces
$scope.messages
#{{message}}
that S
This issue is with the Binding; Make sure messages is in the $scope.
Check: <input type="text" ng-model="test">
In the controller:
$scope.test = data.message(any string);
If it works then there is definitely a binding issue.
I know is kind of an old question and I am pretty new to all this stuff (laravel, angular, etc) but I think what you were looking for was this:
In order to get the angular scope working here
<li ng-repeat="message in messages">
#{{ message.body }}
</li>
and since the "{{" "}}" is used by laravel, you have to define another way to get the scope, by using $interpolateProvider, like this
var app = angular.module('app', []);
app.config(config);
config.$inject = ['$interpolateProvider'];
function config($interpolateProvider){
$interpolateProvider.startSymbol('<<');
$interpolateProvider.endSymbol('>>');
}
so, then, you change the #{{
<li ng-repeat="message in messages">
<< message.body >>
</li>
Hope it helps someone

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.

AngularJS: can't access object property from factory

I have a beginner issue with my AngularJS very simple code: I'm trying to pass data from a factory to a controller and print the object returned to my view, here's my code:
angular.module('app').factory('blogFactory',function(){
return {
//EDIT
post:{"author":"Bob","name":"smith","content":"some content"},
read: function(){
return this.post;
}
}
});
In the controller:
angular.module('app').controller('MainCtrl',['$scope','blogFactory'], function($scope, blogFactory){
$scope.datas = blogFactory.read();
console.log($scope.datas);});
When I console.log($scope.datas it logs the object fine. In the view I 'm unable to access the object's properties:
<section class="overview">
<article ng-repeat="data in datas">
<p>{{data.name}}</p> //Doesn't display anything
<p>{{data}}</p> // Displays the object
</article>
</section>
Does anyone has any idea? Thanks in advance
You don't have any property called name in $scope.datas
{"author":"Bob","content":"some content"}
You must be printing datas.author.
That's why <p>{{data.name}}</p> doesn't display any data.
As per your factory code, post is an object. But in your view you are using
<article ng-repeat="data in datas">
Which is not required. Just datas is enough to get that individual post
This code works fine I have tested it:
var app = angular.module('app',[])
app.factory('blogFactory',function(){
return {
post:{"author":"Bob","content":"some content"},
read: function(){
return this.post;
}
}
});
app.controller('MainCtrl', function($scope,blogFactory){
alert();
$scope.datas = blogFactory.read();
console.log($scope.datas);
})
For the view:
<body ng-controller ="MainCtrl">
<section class="overview">
<article ng-repeat="data in datas" >
<p>{{data.name}}</p>
<p>{{data}}</p>
</article>
</section>
</body>

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