Accessing angular scope value in controller from ng-repeat input box - javascript

I was wondering how to get access to the $scope value from an input box, which happens to be in an ng-repeat, inside of the controller.
View
<div ng-repeat="item in items track by $index">
<form ng-submit="addItem(item, $index)">
<input ng-model="newItem.value" type="text"></input>
</form>
</div>
Controller
$scope.addItem = function(item, index) {
var itemVal = $scope.newItem.value;
console.log(itemVal);
}
The main problem is that I can't access the value from either of the input boxes inside of the controller.
code has been simplified for this quesiton
Really appreciate any help. Thanks

I believe you have only single value, which you want to show inside ng-repeat then Do initialize newItem inside controller like
$scope.newItem = {}
Because of newItem initialization on controller level, ng-repeat will never create a new child scope for it, it will reuse the one parent has created.

If you need one input per item, you need to keep one new model for each item somewhere.
If items is a list, you can keep these newItems in a separate list (jsfiddle):
View
<div ng-repeat="item in items track by $index">
<form ng-submit="addItem(item, $index)">
<input ng-model="newItems[$index]" type="text"></input>
</form>
</div>
Controller
$scope.newItems = [];
$scope.addItem = function(item, index) {
var itemVal = $scope.newItems[index];
console.log(itemVal);
}

Related

Changing ng-model value when using ng-repeat and $index

I have a set of divs, inside a ng-repeat. When I use a ng-model for these, they are all updating when I change the value of this model from a function in the controller. i.e., If I change the model, all the divs are reflecting the same value.
Html:
<tbody ng-repeat="aw in aws">
<div ng-model="currentValue" ng-init="initializeSelects(aw.id)">{{currentValue}}</div>
Controller code:
$scope.initializeSelects = function(awId)
{
$scope.currentValue = "read";
}
I tried changing my code to:
<tbody ng-repeat="(i, aw) in aws track by $index">
<div ng-model="currentValue[i]" ng-init="initializeSelects(aw.id, i)">{{currentValue[i]}}</div>
and
$scope.initializeSelects = function(awId, i)
{
$scope.currentValue[i] = "read";
}
In this case, currentValue always is undefined and the model value can not be changed. Why would it be undefined?
Any inputs would be helpful, thanks in advance!

binding to controller object in Angular

I'm new to angular, trying to bind an an element's content into the controller's Scope to be able to use it within another function:
here is the scenario am working around:
I want the content of the <span> element {{y.facetName}} in
<span ng-model="columnFacetname">{{y.facetName}}</span>
to be sent to the controller an be put in the object $scope.columnFacetname in the controller
Here is a snippet of what I'm working on:
<div ng-repeat="y in x.facetArr|limitTo: limit track by $index ">
<div class="list_items panel-body ">
<button class="ButtonforAccordion" ng-click="ListClicktnColumnFilterfunc(); onServerSideButtonItemsRequested(ListClicktnColumnFilter, myOrderBy)">
<span>{{$index+1}}</span>
<span ng-model="columnFacetname">{{y.facetName}}</span>
<span>{{y.facetValue}}</span>
</button>
</div>
</div>
angular.module('mainModule').controller('MainCtrl', function($scope, $http) {
$scope.columnFacetname = "";
$scope.ListClicktnColumnFilter = "";
$scope.ListClicktnColumnFilterfunc = function() {
$scope.ListClicktnColumnFilter = "\":\'" + $scope.columnFacetname + "\'";
};
}
the problem is that the $scope.ListClicktnColumnFilter doesn't show the $scope.columnFacetname within it, meaning that the $scope.columnFacetname is not well-binded.
In your ng-click instead of calling two different function
ng-click="ListClicktnColumnFilterfunc(); onServerSideButtonItemsRequested(ListClicktnColumnFilter, myOrderBy)"
you can declare like this
ng-click="columnFacetname = y.facetName; onServerSideButtonItemsRequested(columnFacetname , myOrderBy)"
You are trying to pass that model to another function by assigning it to ListClicktnColumnFilter in your controller
By doing in this way, you can achieve the same thing.
I have done one plunker with sample array,
http://embed.plnkr.co/YIwRLWXEOeK8NmYmT6VK/preview
Hope this helps!

How to add multiple items to a list

I'm building an app where users can add items to a list and I decided, for the sake of learning, to use Angular (which I'm very new to). So far, I've been able to successfully add a single item to that list without any issues. Unfortunately, whenever I try to add more than one without a page refresh, I get an error - specifically a "Undefined is not a function."
I've spent more time than I care to think about trying to resolve this issue and I'm hoping an expert out there can give me a hand. Here's what I have so far:
Controllers:
angular.module('streakApp')
.controller('StreakController', function($scope) {
// Removed REST code since it isn't relevant
$scope.streaks = Streak.query();
// Get user info and use it for making new streaks
var userInfo = User.query(function() {
var user = userInfo[0];
var userName = user.username;
$scope.newStreak = new Streak({
'user': userName
});
});
})
.controller('FormController', function($scope) {
// Works for single items, not for multiple items
$scope.addStreak = function(activity) {
$scope.streaks.push(activity);
$scope.newStreak = {};
};
});
View:
<div class="streaks" ng-controller="FormController as formCtrl">
<form name="streakForm" novalidate >
<fieldset>
<legend>Add an activity</legend>
<input ng-model="newStreak.activity" placeholder="Activity" required />
<input ng-model="newStreak.start" placeholder="Start" type="date" required />
<input ng-model="newStreak.current_streak" placeholder="Current streak" type="number" min="0" required />
<input ng-model="newStreak.notes" placeholder="Notes" />
<button type="submit" ng-click="addStreak(newStreak)">Add</button>
</fieldset>
</form>
<h4>Current streaks: {{ streaks.length }}</h4>
<div ng-show="newStreak.activity">
<hr>
<h3>{{ newStreak.activity }}</h3>
<h4>Current streak: {{ newStreak.current_streak }}</h4>
<p>Start: {{ newStreak.start | date }}</p>
<p>Notes: {{ newStreak.notes }}</p>
<hr>
</div>
<div ng-repeat="user_streak in streaks">
<!-- Removed most of this for simplicity -->
<h3>{{ user_streak.fields }}</h3>
</div>
</div>
Could you post the html of StreakController too? Your solution works fine in this fiddle:
http://jsfiddle.net/zf9y0yyg/1/
.controller('FormController', function($scope) {
$scope.streaks = [];
// Works for single items, not for multiple items
$scope.addStreak = function(activity) {
$scope.streaks.push(activity);
$scope.newStreak = {};
};
});
The $scope inject in each controller is different, so you have to define the "streaks" in FormController.
Your problems comes from :
.controller('FormController', function($scope) {
// Works for single items, not for multiple items
$scope.addStreak = function(activity) {
$scope.streaks.push(activity);
^^^^^^
// Streaks is initialized in another controller (StreakController)
// therefore, depending of when is instantiated StreakController,
// you can have an error or not
$scope.newStreak = {};
};
});
A better design would be to implement a StreakService, and to inject that service in the controller you need it. Of course, initializing $scope.streaks in FormController will make your code work, but that's not the responsibility of FormController to initialize this data.
I assume FormController is a nested controller of StreakController, so they share the same scope.
if that works for single object, it should work for mulitiple objects, the problems is you can't just use push to push an array of object to the streaks, you can for loop the array and add them individually or use push.apply trick. I thought the reason of Undefined is not a function. is because the Stack.query() return an element instead of an array of elements so, the method push doesn't exists on the $scope.streaks.
http://jsbin.com/jezomutizo/2/edit

How to add items to a specific dictionary within an item in a list with AngularFire?

The below code shows a list from firebase and shows a corresponding comment field for each item in the list. The user can make a comment on that item and it will update the comment field for that item in the list. Currently, each time a comment is made, it overwrites the previous one, but I'd like for all comments to be saved.
How do I make it so that every time a comment is added, the previous ones are saved as well?
http://jsfiddle.net/chrisguzman/PS9J2/
indx.html
<div ng-app="MyApp" ng-controller="MyCtrl">
<div ng-repeat="(id,item) in data">
<h2>{{item.title}}</h2>
<input ng-model="item.comment"></input>
<button type="submit" ng-click="CommentAdd(id)">Comment</button>
</div>
</div>
app.js
angular.module('MyApp', ['firebase'])
.controller('MyCtrl',
function MyCtrl($scope, $firebase) {
var furl = "https://helloworldtest.firebaseio.com";
var ref = new Firebase(furl);
$scope.data = $firebase(ref);
$scope.CommentAdd = function (id) {
$scope.data.$save(id);
};
});
The following is the data structure within firebase that is generated
{helloworldtest:
{-JSQhsAnY5zhf0oVKfbb: {title: "nameA", comment:"Second Comment"},
-JSQhsAnY5zhf0oVKfbb: {title: "nameB", comment:"Second Comment"}}
}
However, I'd like to create the following where there is a 'comments' branch that holds all comments.
{helloworldtest:
{-JSQhsAnY5zhf0oVKfbb: {title: "nameA", comments:{-JSQhsAnY5zhf0oVKfbb:{Comment:"Second Comment"},-JSQhsAnY5zhf0oVKfbb:{Comment:"First Comment"}}},
{-JSQhsAnYdfdfdffbb: {title: "nameA", comments:{-JSQhsAnY5zhf0oVKfAb:{Comment:"Another Comment"},-JSQhsAnY5zhf0oVKfbb:{Comment:"First Comment"}}}
}
I've tried to do this by replacing
$scope.data.$save(id);
with
$scope.data.$add(id);
I've also tried using :
$scope.data[id].$add({foo: "bar"})
You are saving the comment into a field called comment. Instead, use a list called comments and utilize push or $add.
<div ng-app="MyApp" ng-controller="MyCtrl">
<div ng-repeat="(id,item) in data">
<h2>{{item.title}}</h2>
<input ng-model="newComment"></input>
<button type="submit" ng-click="addComment(id, newComment)">Comment</button>
</div>
</div>
function MyCtrl($scope, $firebase) {
var furl = "https://helloworldtest.firebaseio.com";
var ref = new Firebase(furl+'/items');
$scope.data = $firebase(ref);
var $comments = $firebase( commentsRef );
$scope.addComment = function (id, newComment) {
ref.child(id).child('comments').push(newComment);
};
});
Also Don't nest data just because you can. Instead, consider putting comments in their own path, items in their own path.

AngularFire 3-way data binding is not updating firebase when a checkbox change

I'm developing a simple todo app with Angular and Firebase using AngularFire module.
So I have a boolean attribute in my model represented by a checkbox in the template, the problem is that I'm trying to use the three way data binding from AngularFire using the $bind method to keep the all changes syncronized (firebase data, DOM and ng-model) but the firebase data is not updating when I select a checkbox.
Here's my controller where I'm using the AngularFire $bind method:
angular.module('singularPracticeApp')
.controller('TodoCtrl', ['$scope', 'TodoService', function ($scope, todoService) {
$scope.todos = todoService;
$scope.todos.$bind($scope, 'todo.done');
$scope.addTodo = function () {
$scope.todos.$add({text: $scope.todoText, done:false});
$scope.todoText = '';
};
$scope.remaining = function () {
var count = -11;
angular.forEach($scope.todos, function(todo){
count += todo.done? 0 : 1;
});
return count;
};
$scope.clear = function (id) {
$scope.todos.$remove(id);
};
}]);
And here is the tempalte file:
<div ng-controller="TodoCtrl">
<h4>Task runner</h4>
<span>{{remaining()}} todos left.</span>
<ul>
<li ng-repeat="(id, todo) in todos">
<input type="checkbox" ng-model="todo.done">
<span ng-if="todo.done" style="color: #ddd;">{{todo.text}}</span>
<span ng-if="todo.done == false">{{todo.text}}</span>
<small ng-if="todo.done">clear</small>
</li>
</ul>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText" placeholder="New todo item">
<input type="submit" class="btn btn-primary" value="add">
</form>
</div>
Am I missing something? Is really possible to make this work with a simple checkbox?
Thanks in advance.
You haven't included todoService here so it's going to be difficult to give you an accurate answer. I'll assume that todoService returns a $firebase instance containing the todos since that seems likely. Keep in mind that the problem could be in that code as well.
Several problems you can address, which may resolve your issue:
Your TodoCtrl is not per-item
You seem to be using TodoCtrl as if it were created per-item in the ng-repeat. However, it exists outside the scope of ng-repeat and is only created once for the entire list.
Ng-repeat does not re-use your existing controller scope.
Directives operate in an isolate scope. That means that they do not share scope with your controller. So when you do ng-repeat="todo in todos" you do not add todo into your controller's scope.
This makes sense since each ng-repeat iteration would overwrite the same todo object.
You are trying to double-bind to a synchronized object
You are trying to create a three-way binding $scope.todos.[$todo].done, but you have already created a three-way binding on $scope.todos. Instead, let $scope.todos take care of synchronization.
You've attempted to bind $scope.todos to a property in itself
When you call $bind, you are binding $scope.todos to $scope.todos.todo.done. Obviously this self-referential statement isn't what you intended. I can't tell what is returned by your service but maybe you meant this:
todoService.$bind($scope, 'todos');
If you don't want to automatically push changes on the entire todos list, you can add a $save call instead of using $bind:
$scope.todos = todoService;
<input type="checkbox" ng-model="todo.done" ng-change="$parent.todos.$save(id)">
All together:
angular.module('singularPracticeApp')
.service('todoService', function($firebase) {
return $firebase( new Firebase(URL_TO_TODOS_LIST) );
});
.controller('TodoCtrl', function($scope, todoService) {
todoService.$bind($scope, 'todos');
$scope.addTodo = function () {
$scope.todos.$add({text: $scope.todoText, done:false});
$scope.todoText = '';
};
/** ... and so on ... **/
});

Categories

Resources