I am trying to split a single string into array or JSON format. Kindly help in doing that in angular js controller (not in HTML view).
The string format is like,
string="Name1;Email1;ID1~Name2;Email2;ID2"
None of the ways I tried worked. I tried using string.split('~') but I am getting an error as split is not a function.
myView.service('ViewService', [function () {
var temp = [];
var fstring = [];
this.SplitUser = function (userstring) {
debugger;
//temp = userstring.split('~');
angular.forEach(userstring, function (value, key) {
fstring.push({
'Name': temp.split(';')[i],
'EmailID': temp.split(';')[i++],
'ID': temp.split(';')[i++]
});
})
console.log(temp);
console.log(fstring);
return temp;
}
Need to loop the temp array.not userstring.Also when you are pushing to the fstring array remove the i and use the position as a number
fstring.push({
'Name': value.split(';')[0],
'EmailID': value.split(';')[1],
'ID': value.split(';')[2]
);
change your service like this.
.service('ViewService', [function () {
var temp = [];
var fstring = [];
this.SplitUser = function (userstring) {
debugger;
temp = userstring.split('~');
angular.forEach(temp, function (value, key) {
fstring.push({
'Name': value.split(';')[0],
'EmailID': value.split(';')[1],
'ID': value.split(';')[2]
});
})
console.log(temp);
console.log(fstring);
return temp;
}
}])
Demo
angular.module("app",[])
.controller("ctrl",function($scope,ViewService){
var string="Name1;Email1;ID1~Name2;Email2;ID2";
ViewService.SplitUser(string)
}).service('ViewService', [function () {
var temp = [];
var fstring = [];
this.SplitUser = function (userstring) {
debugger;
temp = userstring.split('~');
angular.forEach(temp, function (value, key) {
fstring.push({
'Name': value.split(';')[0],
'EmailID': value.split(';')[1],
'ID': value.split(';')[2]
});
})
console.log(temp);
console.log(fstring);
return temp;
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
</div>
var string = "Name1;Email1;ID1~Name2;Email2;ID2";
// Initial split in entries
var splitStrings = string.split('~');
var objects = [];
for(var i = 0; i < splitStrings.length; i++) {
// split into properties
var objProps = splitStrings[i].split(';');
var myObj = {};
myObj.name = objProps[0];
myObj.mail = objProps[1];
myObj.id = objProps[2];
objects.push(myObj);
}
console.log(objects);
This should split your string and put it into objects. Then add those objects into an array.
If you want to use JSON and have control over the code that sends you the message I would suggest you use JSON.parse() and JSON.stringify() instead.
This sollution expect a strict structure like the one you posted and has no eror handling.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = [];
var string="Name1;Email1;ID1~Name2;Email2;ID2"
var arr = string.split('~');
angular.forEach(arr, function (value, key) {
$scope.name.push({
'Name': value.split(';')[0],
'EmailID': value.split(';')[1],
'ID': value.split(';')[2]
});
})
console.log($scope.name);
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
</body>
</html>
Related
I have a function below that works fine and passes info into and retrieves from a cookieStore without issue
$scope.num = 0
$scope.nums = []
$scope.increment = function () {
$scope.num++
}
$scope.$watch('num', function () {
$scope.nums.push($scope.num)
})
$scope.storeProductsInCookie=function(){
$cookieStore.put("invoices",$scope.nums)
};
$scope.getProductsInCookie=function(){
console.log( $cookieStore.get("invoices",$scope.nums));
}
However when I try with the below verufyGuess function that is injecting the Index and no as parameters into the function it fails to place into the cookieStore
$scope.verifyGuess = function (Index , no) {
$scope.votes = {};
$scope.newVotes = []
$scope.votes[Index] = $scope.votes[Index] || 0;
$scope.votes[Index]+= no;
$scope.$watch('votes', function () {
$scope.newVotes.push($scope.votes)
})
$scope.storeProductsInCookie=function(){
$cookieStore.put("invoices",$scope.newVotes)
};
$scope.getProductsInCookie=function(){
console.log( $cookieStore.get("invoices",$scope.newVotes));
}
$cookieStore is Deprecated: (since v1.4.0)
Please use the $cookies service instead.
$scope.nums is an array of strings.So $cookieStore is storing them as string(cookies only support strings to store).
In second case $scope.newVotes is an array of objects. cookies wont store objects.
you must use $cookieStore.put("invoices", JSON.stringify($scope.newVotes))
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.12/angular-cookies.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<script>
var app = angular.module('plunker', ['ngCookies']);
app.controller('MainCtrl', function($scope, $cookies) {
$scope.votes = {};
$scope.newVotes = []
var Index = 0;
$scope.votes[Index] = $scope.votes[Index] || 0;
$scope.votes[Index] += 10;
$scope.newVotes.push($scope.votes)
$scope.storeProductsInCookie = function() {
$cookies.put("invoices", JSON.stringify($scope.newVotes))
};
$scope.getProductsInCookie = function() {
console.log($cookies.get("invoices"));
}
$scope.storeProductsInCookie();
$scope.getProductsInCookie();
});
</script>
</body>
</html>
So I am getting an angular [$injector:unpr] error. Yes, I know what that normally means...I haven't defined something somewhere, or I am redefining the module over and over, or the like...but for the life of me I'm struggling to see the issue in my code.
I'm sure I'm missing something insanely basic, but after I've stared at code for a couple of hours, I go blind to it.
My HTML File:
<!DOCTYPE html>
<html ng-app="email">
<head>
<meta charset="UTF-8">
<title>Authentication</title>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700' rel='stylesheet' type='text/css'/>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
</head>
<body>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
<div ng-controller="EmailAuthController as auth">
<h1>Authentication</h1>
<p>Request: [{{auth.request}}]</p>
<p>{{auth.response}}</p>
<p>{{1+2}}</p>
</div>
<script type="text/javascript" src="js/controllers/email.js"></script>
</body>
</html>
My email.js file (As you can see, I've commented out some stuff to try to isolate the issue):
/* global angular parseGet */
function parseGet(val) {
var result = '', // = "Not found",
tmp = [];
var items = location.search.substr(1).split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split('=');
if (tmp[0] === val) {
result = decodeURIComponent(tmp[1]);
}
}
return result;
}
(function () {
angular
.module('email', [])
.controller('EmailAuthController', [ '$scope','authFactory', function ($scope,authFactory) {
var vm = this,
req = parseGet('hash') || '';
vm.request = req;
// authFactory.validate(req)
// .then(function (response) {
// vm.response = response.data;
// });
}])
.factory('authFactory', [ '$rootScope', '$http', 'config', function ($rootScope, $http, config) {
var validate = function (hash) {
var url = config.SERVICE_URI + '/auth/email/' + hash;
return $http.get(url);
};
return {
validate: validate
};
}]);
})();
From the code you've given it appears config is not defined in your authFactory injection.
.factory('authFactory', [ '$rootScope', '$http', 'config', function(a, b, c) {} ]); // config is not defined
I have my model in a Service, all my model is in an object, I would like to be able to reset my model by just reassign my model to an empty object, but it doesn't seem to work, but if I delete a property directly it does.
How could I reset my model without having to delete every property, refresh the page or doing big changes?
(function () {
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function (MyService) {
var _this = this;
_this.model = MyService.model;
_this.myService = MyService;
_this.deleteInService = function () {
MyService.functions.resetModel();
};
});
myApp.service('MyService', function () {
var obj = {};
obj.model = {x: 1};
obj.functions = {};
obj.functions.resetModel = function () {
//delete obj.model.x; //THIS WORKS!
obj.model = {x: 1}; //BUT THIS DOESN'T :(
};
return obj;
});
})();
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script src="changingModelInService.js"></script>
</head>
<body ng-app="myApp" ng-controller="MyController as myCtrl">
{{myCtrl.model.x}}<div><input ng-model="myCtrl.model.x"/></div>
<button ng-click="myCtrl.deleteInService()">Delete X in service</button>
</body>
</html>
Thank you.
Edit: doing _this.model = MyService.model it's not possible because I share my Service with many controllers
I think one solution to your problem would be to create a default model variable like a master copy and use angular.copy with two parameters resetting the model to a master version when invoking that method.
See the angular.copy documentation here. You'll notice the live demo actually shows a reset functionality.
I've updated the live demo plunker to show the behaviour I think you desire http://plnkr.co/edit/BJ....
Hope that helps!
UPDATE::
A possible implementation although will require testing would be as follows;
myApp.service('MyService', function () {
var masterModel = {x: 1};
var obj = {
model: {x: 1},
functions: {
resetModel: function() {
angular.copy(masterModel, obj.model);
}
}
};
return obj;
});
Other than angular.copy, another solution is just to not use _this.model and use _this.myService.model instead or to change your deleteInService function to
_this.deleteInService = function () {
MyService.functions.resetModel();
_this.model = MyService.model;
};
The reason you're getting this problem is because you're doing something like this:
service.model = foo;
controller.model = service.model; // implies controller.model = foo;
service.reset(); // => service.model = bar;
// But notice that controller.model still points to the old object foo
Run the code snippet below to see what I mean.
(function () {
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function (MyService) {
var _this = this;
_this.model = MyService.model;
_this.serviceModel = MyService.model;
_this.myService = MyService;
_this.deleteInService = function () {
MyService.functions.resetModel();
_this.serviceModel = MyService.model;
};
});
myApp.service('MyService', function () {
var obj = {};
obj.model = {x: 1};
obj.functions = {};
obj.functions.resetModel = function () {
//delete obj.model.x; //THIS WORKS!
obj.model = {x: 1}; //BUT THIS DOESN'T :(
};
return obj;
});
})();
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<script src="changingModelInService.js"></script>
</head>
<body ng-app="myApp" ng-controller="MyController as myCtrl">
<pre>myCtrl.model = {{myCtrl.model}}</pre>
<pre>myCtrl.serviceModel = {{myCtrl.serviceModel }}</pre>
<pre>myCtrl.myService.model = {{myCtrl.myService.model}}</pre>
<div><input ng-model="myCtrl.model.x"/></div>
<button ng-click="myCtrl.deleteInService()">Delete X in service</button>
</body>
</html>
var myApp = angular.module("myApp", ["firebase"]);
var nick = prompt("Anna nimesi");
myApp.controller("MyController", ["$scope", "$firebaseArray",
function($scope, $firebaseArray) {
var msgref = new Firebase("https://(myapp).firebaseio.com/messages");
var usrref = new Firebase("https://(myapp).firebaseio.com/users");
$scope.messages = $firebaseArray(msgref);
$scope.users = $firebaseArray(usrref);
console.log($scope.users);
console.log($scope.messages);
var taken = false;
angular.forEach($scope.users, function(value, key) {
console.log(value, key);
if (value.username == nick) {
taken = true;
}
// put your code here
});
if (taken == false) {
$scope.users.$add({
username: nick
});
};
$scope.addMessage = function(e) {
if (e.keyCode == 13 && $scope.msg) {
var name = nick || "anynomous";
$scope.messages.$add({
from: name,
body: $scope.msg
});
$scope.msg = "";
}
}
}
])
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
<title>title</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.1.1/angularfire.min.js"></script>
</head>
<body ng-controller="MyController">
<div class="example-chat l-demo-container">
<ul id="example-messages" class="example-chat-messages">
<li ng-repeat="msg in messages">
<strong class="example-chat-username">{{msg.from}}</strong>
{{msg.body}}
</li>
</ul>
</div>
<input class="input" autofocus="true" ng-model="msg" ng-keydown="addMessage($event)" type="text" id="messageInput" placeholder="kirjota">
<script src="script.js"></script>
</body>
</html>
Im doing a chat, and i want to check if there is already a user with same name, so that there could not be two users with same nick. This does not work, and i can add many same nicks.
var usrref = new Firebase("https://(myapp).firebaseio.com/users");
$scope.users = $firebaseArray(usrref);
var taken = false;
for (var usr in $scope.users) {
if(usr.username == nick){
taken = true;
};};
if(taken == false){
$scope.users.$add({username:nick});
};
My messages is showing perfectly with ng-repeat in html, but i cant get this work. Its obviously something simple, but i have struggled too long with this.
Since you're using Angular, I'd suggest using Angular's forEach method. Here's an example of what you could do:
angular.forEach($scope.users, function(value, key) {
// put your code here
});
Edited
This should work for you. It checks your data after it has been loaded from Firebase. If the username is present, then it doesn't add the name. If it is not present, then it's added. You could check out the AngularFire API for $loaded().
var addNameToArray = true;
$scope.users.$loaded().then(function(data) {
angular.forEach(data, function(value, key) {
if(value.username === "John") {
addNameToArray = false;
}
});
if(addNameToArray) {
$scope.users.$add({username: "John"});
}
});
A for (var ... in ...) iterates over object keys. So if $scope.users is an array you'll get indexes: 0, 1, 2, ... in the usr variable. To iterate over an array you can use for example following construct:
$scope.users.forEach(function(user) {
});
But maybe instead of using an array it would be better to use an object indexed by username. Then you'll get immediate information if given user exists (users[nick] !== undefined) and you'll also avoid some other trouble. See Best Practices: Arrays in Firebase.
I have a small problem and I don't understand this thing:
When I add an item to TestiFactorys arr - array it does update to both controllers
On the other hand why does not TestiFactorys arr_len update to both controllers. And in TestiController why do I have to "manually" update TestControllers list1_length to make it update to view but I don't have to update TestiContollers list1 to make it update to view
I am assuming that my poor Javascript or Javascript variable scope understanding is causing this but i just don't see it.
I am using AngularJS version 1.2.16
<!DOCTYPE html>
<html ng-app="TestiApp">
<head>
<title></title>
</head>
<body>
<div ng-controller="TestController">
List items from controller: {{list1}}<br>
List item count:{{list1_length}}
<input type="text" ng-model="param"><br>
<button ng-click="list1_add(param)">asd</button>
</div>
<br><br>
<div ng-controller="TestController2">
List items from controller2{{list2}} <br>
List items count in from controller2: {{list2_length}}
</div>
<script src="scripts/angular.min.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
And this is my app.js:
var TestiApp = angular.module('TestiApp', [])
TestiApp.factory('TestiFactory',function() {
var arr = ['abx','cbs'];
var arr_len = arr.length;
return {
list : function() {
return arr;
},
add_to_arr : function(n) {
arr.push(n);
},
arr_len : function() {
arr_len = arr.length;
return arr_len;
}
}
}
);
TestiApp.controller('TestController', function($scope, TestiFactory) {
$scope.list1 = TestiFactory.list();
$scope.list1_length = TestiFactory.arr_len();
$scope.list1_add = function (d) {
TestiFactory.add_to_arr(d);
$scope.param = '';
$scope.list1_length = TestiFactory.arr_len();
}
});
TestiApp.controller('TestController2', function($scope, TestiFactory) {
$scope.list2 = TestiFactory.list();
$scope.list2_length = TestiFactory.arr_len();
});
EDIT WITH SOLUTION
Here is working solution. Based to comments I decided to do more studying on Javascripts basics which
is of course the thing I should have done before trying to use this complex framework which uses Javascript. So now I have some basic understanding how to use references in Javascript and what primitive data types are. And based on that here is working version:
<!DOCTYPE html>
<html ng-app="TestiApp">
<head>
<title></title>
</head>
<body>
<div ng-controller="TestController">
List items from controller: {{list1()}}<br>
List item count:{{list1_len()}}
<input type="text" ng-model="param"><br>
<button ng-click="list1_add(param)">asd</button>
</div>
<br><br>
<div ng-controller="TestController2">
List items from controller2{{list2()}} <br>
List items count in from controller2: {{list2_length()}}
</div>
<script src="scripts/angular.min.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
And app.js:
var TestiApp = angular.module('TestiApp', [])
TestiApp.factory('TestiFactory',function() {
var arr = ['abx','cbs'];
return {
list : function() {
return arr;
},
add_to_arr : function(n) {
arr.push(n);
},
arr_len : function() {
return arr.length;
}
}
}
);
TestiApp.controller('TestController', function($scope, TestiFactory) {
$scope.list1 = TestiFactory.list;
$scope.list1_add = TestiFactory.add_to_arr;
$scope.list1_len = TestiFactory.arr_len;
});
TestiApp.controller('TestController2', function($scope, TestiFactory) {
$scope.list2 = TestiFactory.list;
$scope.list2_length = TestiFactory.arr_len;
});
I've ran into this many times. Factories and services in angular are not like scopes...they work using references. The reason the array updates in your controllers is because the original reference was updated. The length is not updating because the number type is primitive.
This should work:
TestiApp.controller('TestController', function($scope, TestiFactory) {
$scope.list1 = TestiFactory.list();
$scope.$watch('list1', function(list1) {
$scope.list1_length = list1.length;
});
$scope.list1_add = function (d) {
TestiFactory.add_to_arr(d);
$scope.param = '';
};
});
TestiApp.controller('TestController2', function($scope, TestiFactory) {
$scope.list2 = TestiFactory.list();
$scope.$watch('list2', function(list2) {
$scope.list2_length = list2.length;
});
});