AngularJS : what's the difference between these two lines? - javascript

$scope.init = function() {
return $scope.items = basketService.items;
};
ng-repeat = "item in items"
And working with $scope.items + refresh $scope.items with broadcasting.
OR
$scope.getItems = function() {
return basketService.items;
};
ng-repeat = "item in getItems()"
Is copying basketService.items to $scope.items a must done or is it the same as getItems() (speed, memory...) ?

I don't believe there is a difference between them, and it is really just a matter of style. Take a look at this (very crude and contrived) fiddle I created: http://jsfiddle.net/digitalzebra/92gA6/
Here is the very messy controller from that:
angular.module("foobar", []).controller("lol", function($scope) {
$scope.items = ["loe", "le", "effe"];
var blah = ["leoele", "elelkej", "elfkjflkje"];
$scope.doStuff = function() {
$scope.items.push("eee", "eeelkjf");
};
$scope.getItems = function() {
return blah;
}
$scope.doOtherStuff = function() {
blah.push("elejlee'e");
};
});
And here is my HTML:
<div ng-app="foobar">
<div ng-controller="lol">
<b>First list:</b>
<div ng-repeat="item in items">
{{item}}
</div>
<b>Second list:</b>
<div ng-repeat="item in getItems()">
{{item}}
</div>
<button ng-click="doStuff()">Click me</button>
<button ng-click="doOtherStuff()">Do Other stuff</button>
</div>
</div>
Notice that both variants work, and both will give you two way binding etc.

Related

ng-repeat Drop-down to restrict selecting same value multiple times

I have a drop-down inside ng-repeat and a add button that can add new drop-down to the list as I've shown in the JSFiddle, and I want to restrict the second drop-down to select the first selected value in the second drop-down. So the value selected in the first drop-down should not allowed to select in the second or hide that value.
In my old question pankaj parkar given the answer,But I am unable to integrate that answer in my JSFiddle.
ng-repeat="post in posts | filter: { type: selectedValue }"
Please help me on this.
This is my old question
My JSFiddle.
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.names = ['Mobile','Office','Home'];
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset ng-model='y' ng-repeat="choice in choices">
<select>
<option ng-model='x1' ng-repeat = "x in names">{{x}}</option>
</select>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
</div>
Put your options in scope items array. Get your output result from choices array.
var app = angular.module('angularjs-starter', []);
app.filter("itemFilter", function(){
return function(items, choice){
filtered_items=[];
for(var i=0;i<items.length;i++){
if(items[i].choiceID==null || items[i].TYPE_ID==choice.TYPE_ID)
filtered_items.push(items[i]);
}
return filtered_items;
}
});
app.controller('MainCtrl', function($scope) {
$scope.items = [
{"TYPE_ID":1,"TYPE_NAME":"Jpeg"},
{"TYPE_ID":2,"TYPE_NAME":"Odt"},
{"TYPE_ID":3,"TYPE_NAME":"docx"},
{"TYPE_ID":4,"TYPE_NAME":"xls"}
];
$scope.choices = [];
$scope.addNewChoice = function() {
var newChoiceID = 'choice'+$scope.choices.length+1;
for(var i=0;i<$scope.items.length;i++){
if($scope.items[i].choiceID==null){
$scope.items[i].choiceID = newChoiceID;
$scope.choices.push({'id':newChoiceID,TYPE_ID:$scope.items[i].TYPE_ID});
break;
}
}
};
$scope.updateValue = function(choice) {
for(var i=0;i<$scope.items.length;i++){
if($scope.items[i].choiceID==choice.id)
$scope.items[i].choiceID = null;
if($scope.items[i].TYPE_ID==choice.TYPE_ID)
$scope.items[i].choiceID = choice.id;
}
};
$scope.addNewChoice();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset ng-repeat="choice in choices">
<select ng-model="choice.TYPE_ID" ng-change="updateValue(choice)">
<option ng-repeat = "item in items | itemFilter:choice" value="{{item.TYPE_ID}}">{{item.TYPE_NAME}}</option>
</select>
</fieldset>
<button class="addfields" ng-show="items.length>choices.length" ng-click="addNewChoice()">Add fields</button>
<h4>Data for backend</h4>
<ul>
<li ng-repeat="choice in choices">TYPE_ID: {{choice.TYPE_ID}}</li>
</ul>
</div>
You can try this solution, which works based on the first options selected value, based on the requirement you can change it.
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.names = ['Mobile','Office','Home'];
$scope.selectedValue = [];
$scope.choices = [{id: 'choice1', options: $scope.names}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
// First Frame options list
var ele = document.getElementById('myOptions');
var angularEle = angular.element( ele );
var value = angularEle[0].value;
$scope.selectedValue = $scope.names.filter(item => item !== value)
$scope.choices.push({'id':'choice'+newItemNo, options: $scope.selectedValue});
};
});
.addfields {
-webkit-appearance: button;
cursor: pointer;
color: #fff;
background-color: #337ab7;
border-color: #2e6da4;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div id='mainC' ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset ng-model='y' ng-repeat="choise in choices">
<p> <ul>Id, Options
<li ng-repeat="(k,v) in choise">{{v}}</li>
</ul></p>
<select id='myOptions'>
<option ng-model='x1' ng-repeat = "x in choise.options">{{x}}</option>
</select>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
</div>

How to access a key of an object by its variable name in DOM using angular

I have a controller which adds to scope a variable called comments
$scope.showComments = function(id){
dataService.getComments(id).then(function(data){
$scope.comments[id] = data.comments;
console.log($scope.comments);
});
}
I want to call the ng-repeat on a specific id. The following method is not working. Any ideas?
<div class="commentsContainer" id="{{id}}">
<div class="eachcomment" ng-repeat="comment in comments.{{id}}">
<p>{{comment.content}}
</div>
</div>
The desired id is given to the outer div. But ng-repeat is not working.
You should use a filter to achieve this functionality as follows:
<div class="eachcomment" ng-repeat="comment in comments | filterId: id">
<p>{{comment.content}}
</div>
Now, write a filter:
app.filter('filterId', function(){
return function(collection, id) {
var output = [];
angular.forEach(collection, function(item) {
if(item.id == id) {
output.push(item)
}
})
return output;
}
})
Or you can use an easier way:
<div class="eachcomment" ng-repeat="comment in comments | filter: checkId">
<p>{{comment.content}}
</div>
And in your controller:
$scope.checkId = function(item) {
if($scope.id == item.id) {
return true;
}
return false;
}
You can do that with:
<div ng-app="myApp" ng-controller="dummy">
<div class="commentsContainer" id="{{id}}">
<div class="eachcomment" ng-repeat="(key, comment) in comments">
<p ng-show="key === id">{{comment.content}}</p>
</div>
</div>
</div>
JS:
angular.module('myApp', [])
.controller('dummy', ['$scope', function ($scope) {
$scope.id = 0;
$scope.comments = [{
content: 'Hello'
}, {
content: 'World'
}];
}]);
JSFiddle
You should use bracket notation to access property by variable key:
<div class="commentsContainer" id="{{id}}">
<div class="eachcomment" ng-repeat="comment in comments[id]">
<p>{{comment.content}}
</div>
</div>

AngularJS directive templates ng-repeat funny substitution

I'm struggling with angularjs directive templates. The {{variable}} works in a very strange way inside a ng-repeat,
<div ng-controller="MyCtrl">
<h2>here i am</h2>
<button type="button" ng-click="addItem()" class="btn btn-primary">Howdy</button>
<div ng-repeat="item in items track by $index" itemlist></div>
</div>
<script type="text/ng-template" id="template.html">
<div>
Howdy {{item.itemNum}} {{item.name}}
</div>
</script>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.count = 0;
$scope.items = [];
var newItem = {
itemNum: 0,
name: "New"
};
$scope.addItem = function () {
newItem.itemNum = $scope.count;
console.log('adding item ' + newItem.itemNum);
$scope.items.push(newItem);
$scope.count += 1;
};
});
myApp.directive('itemlist', function ($compile) {
return {
templateUrl: 'template.html',
};
});
I have created a jsfiddle showing my problem here: http://jsfiddle.net/dk253/8jm5tjvf/23/.
What am I missing or doing wrong?
Thanks!
The reason is you are updating the property on the same object reference (newItem) every time. So it updates all other items in the array because they all just point to the same object or in other words they are all same. You could instead get the copy of the object using angular.copy and push that item.
var item = {
itemNum: 0,
name: "New"
};
$scope.addItem = function () {
var newItem = angular.copy(item); //Get the copy
newItem.itemNum = $scope.count;
Fiddle

Calling one controller from another in Angular.js

I'm having trouble understanding some of the basics. Here are 2 controllers I have:
<form ng-controller="NewList" id="form" ng-submit="submit()">
<input name="title" ng-model="formData.title" placeholder="{{placeholders.title}}" />
<button type="submit">Generate</button>
<p ng-show="loading == 1">Loading...</p>
<p ng-show="loading == 2">Response: {{response}}</p>
</form>
<div id="lists" ng-controller="GetLists">
<ul>
<li ng-show="loading">Loading...</li>
<li class="list" ng-repeat="list in lists">
<b>{{list.id}}</b> : {{list.title}}
</li>
</ul>
</div>
JS:
function NewList($scope, $http) {
$scope.formData = { };
$scope.placeholders = { "title" : "List title" };
$scope.loading = 0;
$scope.submit = function() {
$scope.loading = 1;
$http.post(window.apiBase + 'lists/create', this.formData)
.success(function(response) {
$scope.response = response;
$scope.loading = 2;
});
}
}
function GetLists($scope, $http) {
$scope.loading = true;
$http.get(window.apiBase + 'lists/all').success(function(response) {
$scope.lists = response.lists;
$scope.loading = false
});
}
What I'm trying to achieve, is upon form submit, refresh the lists. Meaning, when .success() hits in NewList, call GetList and make it happen again. How do I achieve this?

apply filter to ngRepeat from different controller

How do I apply a filter to ngRepeat from a different controller?
From the Filters controller how do I applyFilter():
<div ng-controller="Filters">
<span ng-click="applyFilter()"></span>
</div>
... To items in the Results controller
<div ng-controller="Results">
<div ng-repeat="item in items">
{{item.thing}}
</div>
</div>
You could use either a parent controller or a service. The first example below uses a parent controller to define the items and filter value to share it with the two child controllers. The second example demonstrates the use of a service that is injected to both controllers and doesn't require a parent controller.
Parent Controller example: I would have one parent controller for both and define the data and filter value in that controller. This will allow each child controller to easily process and manipulate the filter:
Demo: http://plnkr.co/edit/yrtsX5SQsRiNSho6o9x8?p=preview
HTML:
<body ng-controller="MainCtrl">
Hello {{name}}!
<div ng-controller="Filters">
<span ng-click="applyFilter()">Apply Filter</span>
</div>
<div ng-controller="Results">
<div ng-repeat="item in items | filter:filterFunc ">
{{item}}
</div>
</div>
</body>
Controllers:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.items = [1,2,3,4,5,6,7];
$scope.filterVal = 0;
});
app.controller('Filters', function($scope) {
$scope.applyFilter = function() {
$scope.$parent.filterVal = 5;
$scope.$apply();
}
});
app.controller('Results', function($scope) {
$scope.filterFunc= function(item) {
console.log(item);
if (item>$scope.filterVal)
return item;
}
});
Services Example. Here is an updated example with a service which contains the filter value and the items. http://plnkr.co/edit/wZFKBMRv0SeEsXNqARe2?p=preview
app.controller('Filters', function($scope, Utils) {
$scope.applyFilter = function() {
Utils.setFilter(4);
}
});
app.controller('Results', function($scope, Utils) {
$scope.items = Utils.getItems();
$scope.filterFunc= function(item) {
console.log(item);
if (item>Utils.getFilter())
return item;
}
});
angular.module('ServicesUtils', []).
factory('Utils', [ function () {
var items = [1,2,3,4,5,6,7];
var filter = 0;
var service = {
getFilter:function() {
return filter;
},
getItems:function() {
return items;
},
setFilter:function(n) {
filter = n;
}
};
return service;
}]);

Categories

Resources