I am using angularjs, I have one for loop and I get the loop values into one variable called Name .Now my need is that variable should store into scope array selection . How to achieve this.
code:
$scope.selection = [];
for(var i=0 ;i<$scope.Streams.length;i++)
{
var Name=$scope.Streams[i].Name;
}
here i add the dynamic value of name into scope array.
I need output of my scope variable like this
Guess you want to add items of $scope.Streams to $scope. selection.
you can use Array.push.
$scope.selection = [];
// option1
for(var i=0 ;i<$scope.Streams.length - 1;i++) {
$scope.selection.push($scope.Streams[i]);
}
// option2 (with new instance)
$scope.selection = $scope.Streams.slice();
// option3
$scope.selection = $scope.Streams;
Try this single line of code with Array.map() method :
$scope.selection = $scope.Streams.map(item => { return {"Name":item.Name} });
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.Streams = [
{
"id":1,
"Name":"stream1"
},
{
"id":2,
"Name":"stream2"
},
{
"id":3,
"Name":"stream3"
}
];
$scope.selection = $scope.Streams.map(item => { return {"Name":item.Name} });
console.log($scope.selection);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
</div>
Related
My question is related to creating substr in Angular.JS
Suppose i have a model:
$scope.myName = 'John Smith'
but when during the rendering of the model on the page i need only the initials of the name like:
<p>{{myName | some directive/filter }}<p>
Output should be :: JS
i tried creating many directives but unable to fetch the exact output even i have tried the limitTo filter but it give only the starting first 2 letters of the name.
Workbook is here
With assumption that name tokens are separated by SPACE , as given in your question
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<label>Name : {{name}}</label><br/>
<label>Short Name : {{name|shortName}}</label>
</div>
<script>
var app = angular.module('myApp', []);
app.filter('shortName', function() {
return function(x) {
var shortName="", nameTokens=[];
nameTokens = x.split(" ");
nameTokens.forEach(function(token){ shortName+=token[0] });
return shortName;
};
});
app.controller('namesCtrl', function($scope) {
$scope.name = 'John Smith';
});
</script>
</body>
angular
.module('myApp',[])
.run(function($rootScope){
$rootScope.title = 'myTest Page';
})
.controller('testController', ['$scope', function($scope){
$scope.myName = 'saurabh raman';
}]).filter('filter', function() {
return function(input) {
var name = input;
var inls = name.match(/\b\w/g) || [];
inls = ((inls.shift() || '') + (inls.pop() || '')).toUpperCase();
return inls;
}
});
view
<p>{{myName | filter}}</p>
</body>
</html>
I was hoping there was a built-in filter for it, but it seems there isn't one, so I've created this filter:
var relConclusaoApp = angular.module("relatorioConclusaoApp", []);
relConclusaoApp.filter('onlyinitials', [function () {
return function (input) {
if (input) {
return input
.split(/\s+/)
.filter(s => s.length > 2)
.map(s => s.charAt(0).toLocaleUpperCase())
.join(".")
.concat(".")
}
return input;
}
}])
This filter is going to transform Floor Jansen into F.J. (e.g.)
It should be used in your template as:
{{nameToBeTransformed | onlyinitials}}
It's an edit form with parent record first populated then dependent select list is populated, and then it's expected the value from parent record pre-select the combo box.
html
<select ng-model="data.trackId" >
<option ng-repeat="track in tracks" value="{{track.id}}">{{track.name}}</option>
initial result once parent record is pulled.
if(data) {
this.$scope.data.id = data.id;
this.$scope.data.name = data.name;
this.$scope.data.room = data.room;
this.$scope.data.start = data.start;
this.$scope.data.end = data.end;
this.$scope.data.dayId = data.day_id;
this.$scope.data.trackId = data.track_id;
this.$scope.data.color = data.color;
this.$scope.data.description = data.description;
this.$scope.$apply();
this.$element[0].removeAttribute("style");
}
//later track results were pulled
trackResult: function(data, status, headers, config) {
for(var i=0; i<data.length; i++) {
this.$scope.tracks.push(data[i]);
}
this.$scope.$apply();
},
Problem:
List gets populated from the second call trackResult but default value from the $scope.trackId never sets the combo box to a value.
Edit: Controller Body
controller: function($scope, $element) {
var self = this;
this.$scope = $scope;
this.$element = $element;
this.$scope.data = {};
this.$scope.days = [];
this.$scope.tracks = [];
this.$scope.submit = function() {self.submit()};
this.$scope.cancel = function() {self.cancel()};
},
Edit : Updated with setting the data from outside the scope (OP request)
Use ng-options & ng-model
this is how i think it should be done in angularjs.
use the built in databinding capabilities to simplify your code and make it less complicated
for binding a list into a <select> and controlling the selected item, this snippet below should do the trick.
http://jsfiddle.net/72em40j4/
js
var myapp = angular.module('myapp', []);
myapp.controller('Ctrl', function ($scope) {
$scope.options = [];
$scope.selectedOption = null;
});
html
<script>
function clickFromOutside() {
var controllerElement = document.getElementById('container');
var controllerScope = angular.element(controllerElement).scope();
var firstTrack = {
id: 1,
first: 'First',
last: 'Track'
};
var secondTrack = {
id: 2,
first: 'Second',
last: 'Track'
};
controllerScope.options.push(firstTrack);
controllerScope.options.push(secondTrack);
controllerScope.selectedOption = secondTrack;
controllerScope.$apply();
}
</script>
<button onclick="clickFromOutside();">outside</button>
<div ng-app="myapp">
<fieldset id="container" ng-controller="Ctrl">
<select ng-options="p.first + ' ' + p.last for p in options" ng-model="selectedOption"></select> <pre>{{ selectedOption }}</pre>
</fieldset>
</div>
Sorry for my bad English.
How to get a list of contacts by using the Cordova angularjs?
Thanks in advance. Kind regards.
I don't know how your cordova-app is built up and but you could do it this way( take into consideration that I've not tested this):
Code:
First request contacts of your device by using the condact-plugin of cordova:
(same link as provided earlier: http://docs.phonegap.com/en/edge/cordova_contacts_contacts.md.html)
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// when using the plugin:
// you can put it within your angularjs-controllers
// where it will be executed and onSuccess-callback is called.
var options = new ContactFindOptions();
options.filter = "";
options.multiple=true;
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
// within this function you have to assign contacts to a model
function onSuccess(contacts) {
$scope.contacts = contacts;
}
function onError(contactError) {
alert('onError!');
}
HTML:
Iterate over each contact-object of your contacts-collection assigned within onSuccess-function:
<div ng-repeat="contact in contacts">{{contact.name.formatted}}</div>
Tutorial: http://www.quora.com/What-is-the-way-to-get-all-contacts-using-PhoneGap-on-Android
Putting the plugin into a angularjs-controller could look like this:
angular.module('aModule', [])
.controller('contactCtrl', ['$scope', function($scope) {
var options = new ContactFindOptions();
options.multiple = true;
options.filter = "";
var fields = ["displayName", "name"];
navigator.contacts.find(fields,
function(contacts){
var arr = [];
for (var i = 0; i < contacts.length; i++)
{
arr.push({name: contacts[i].name.formatted})
}
$scope.contacts = arr;
},
function(error){ console.log(error); },
options
);
}])
HTML:
<div ng-app="aModule" ng-controller="contactCtrl">
<div ng-repeat="contact in contacts">{{contact.name}}</div>
</div>
I want to have an array in the service, which can be modified from different controllers.
The purpose of this is the have an array accessible through every controller.
I want to be able to push items to this array from controllers, as well to delete them.
Service:
.service('EmailOps', function () {
var templates = [];
return {
pushToEmailBody: function (newObj) {
templates.push(newObj);
console.log(templates);
}
};
});
Controller:
angular.module('app')
.controller('mainCtrl', function ($scope, $rootScope, EmailOps) {
$scope.include = EmailOps.pushToEmailBody;
});
HTML:
<div ng-controller="mainCtrl">
1
2
3
</div>
To summarize, I would like to be able to add multiple new elements to the array in the service by clicking on these links. Currently when it adds one of them, it replaces the one added before, so that I have an array with one element only. Any idea what I might be doing wrong?
please see here : http://jsbin.com/gesirira/1/edit
service:
app.service('EmailOps', function () {
var templates = [];
function pushToEmailBody (newObj) {
templates.push(newObj);
console.log(templates);
}
return {
templates:templates,
pushToEmailBody : pushToEmailBody
};
});
controller:
app.controller('firstCtrl', function($scope,EmailOps){
$scope.include = function(obj)
{
EmailOps.pushToEmailBody(obj);
};
$scope.temp = EmailOps.templates;
});
html:
<body ng-app="app">
<div ng-controller="firstCtrl">
1
2
3
<br/>
templates: {{temp |json}}
</div>
</div>
</body>
You can modify your service like this
.service('EmailOps', function () {
this.templates = [];
this.pushToEmailBody = function (newObj) {
templates.push(newObj);
console.log(templates);
}
});
and then in the controller :
$scope.include = function(obj)
{
EmailOps.pushToEmailBody(obj);
};
I'm trying to show two section of my html page with same json data, i don't want to wrap both in same controller as it is positioned in different areas. I have implemented that concept successfully by using local json data in "angular service" see the demo
<div ng-app="testApp">
<div ng-controller="nameCtrl">
Add New
Remove First
<ul id="first" class="navigation">
<li ng-repeat="myname in mynames">{{myname.name}}</li>
</ul>
</div>
<div>
Lot of things in between
</div>
<ul id="second" class="popup" ng-controller="nameCtrl">
<li ng-repeat="myname in mynames">{{myname.name}}</li>
</ul>
JS
var testApp = angular.module('testApp', []);
testApp.service('nameService', function($http) {
var me = this;
me.mynames = [
{
"name": "Funny1"
},
{
"name": "Funny2"
},
{
"name": "Funny3"
},
{
"name": "Funny4"
}
];
//How to do
/*this.getNavTools = function(){
return $http.get('http://localhost/data/name.json').then(function(result) {
me.mynames = result.mynames;
return result.data;
});
};*/
this.addName = function() {
me.mynames.push({
"name": "New Name"
});
};
this.removeName = function() {
me.mynames.pop();
};
});
testApp.controller('nameCtrl', function ($scope, nameService) {
$scope.mynames = nameService.mynames;
$scope.$watch(
function(){ return nameService },
function(newVal) {
$scope.mynames = newVal.mynames;
}
)
$scope.addName = function() {
nameService.addName();
}
$scope.removeName = function() {
nameService.removeName();
}
});
jsfiddle
Next thing i want to do is to make a http request to json file and load my two section with data, and if i add or remove it should reflect in both areas.
Any pointers or exisisitng demo will be much helpful.
Thanks
The reason why only one ngRepeat is updating is because they are bound to two different arrays.
How could it happen? It's because that you have called getNavTools() twice, and in each call, you have replaced mynames with a new array! Eventually, the addName() and removeName() are working on the last assigned array of mynames, so you're seeing the problem.
I have the fix for you:
testApp.service('nameService', function($http) {
var me = this;
me.mynames = []; // me.mynames should not be replaced by new result
this.getNavTools = function(){
return $http.post('/echo/json/', { data: data }).then(function(result) {
var myname_json = JSON.parse(result.config.data.data.json);
angular.copy(myname_json, me.mynames); // update mynames, not replace it
return me.mynames;
});
};
this.addName = function() {
me.mynames.push({
"name": "New Name"
});
};
this.removeName = function() {
me.mynames.pop();
};
});
testApp.controller('nameCtrl', function ($scope, nameService) {
// $scope.mynames = nameService.mynames; // remove, not needed
nameService.getNavTools().then(function() {
$scope.mynames = nameService.mynames;
});
/* Remove, not needed
$scope.$watch(
function(){ return nameService },
function(newVal) {
$scope.mynames = newVal.mynames;
}
);
*/
$scope.addName = function() {
nameService.addName();
};
$scope.removeName = function() {
nameService.removeName();
};
});
http://jsfiddle.net/z6fEf/9/
What you can do is to put the data in a parent scope (maybe in $rootScope) it will trigger the both views ,And you don't need to $watch here..
$rootScope.mynames = nameService.mynames;
See the jsFiddle