Valid json dont work with ng-repeat - angularjs

My response from Java servlet via Angular, the request content is text/html
and I used data.split:
d = response.data.replace(/^\s+|\s+$/g, ''); // remove /r/n
data = d.split(" ");
for(var i =0 ; i<data.length; i++){
data[i] = '{' + data[i] + '}'; // add {} to each k.v
}
The result looks like:
["{key:myKey,value:true}", "{key:myKey,value:true}"....]
And my HTML
<ul>
<li ng-repeat="line in fixedDBArray">
{{line.key}} - {{line.value}}
</li>
</ul>
The anguler data-binding look like:
$scope.fixedDBArray = data //response.data
And {{fixedDBArray}} works fine but {{line.key}} and {{line.value}} do not work. I had checked http://jsonlint.com/ and the json is valid.
Anyone knows what is the problem?

If you still want to fix this as it stands now. you can use replace method and make the value valid JSON object. i made a sample implementation of this here
make sure that you use more efficient regular expression for adding additional quotes.just posting it for your reference without considering performance or complexity.

Related

ng-tags-input not working correctly with autocomplete

I'm adding tag by selecting from list (which is populated using $http request). The tag is added but the text which I have typed that remains there with ng-invalid-tag class.
ScreenShots
1) Initially,
2) Typing 3 letters to get HTTP Call.
3) Now after selection of first Skill "Angular Js'.
4) It shows that .input.invalid-tag is enabled. And which doesn't clear the placeholder.
My Input Tag is as below.
<tags-input ng-model="employerMyCandidatesCtrl.skillList" placeholder="Skills..."
replace-spaces-with-dashes="false"
add-from-autocomplete-only="true"
display-property="skillName"
on-tag-added="employerMyCandidatesCtrl.addTagToSkillData($tag)"
on-tag-removed="employerMyCandidatesCtrl.removeTagFromSkillData($tag)">
<auto-complete
source="employerMyCandidatesCtrl.loadSkillData($query)"
displayProperty="skillName" debounce-delay="500"
min-length="3">
</auto-complete>
</tags-input>
Controller Code is as below.
vm.skillList = [];
vm.loadSkillData = function(query) {
return EmployerServices.getAllSkillsPromise(query); // $http call.
};
vm.addTagToSkillData = function(tag) {
if (_.findIndex(vm.skillList, tag) < 0) {
vm.skillList.push(tag);
}
};
vm.removeTagFromSkillData = function(tag) {
var ind = _.findIndex(vm.skillList, tag) > -1 ? vm.skillList.splice(ind, 1) : '';
};
Is any configuration mistake I'm doing?
There are 4 attributes for onTagAdding, onTagAdded, onTagRemoving, onTagRemoved so the basic difference between the attributes ending with adding compared to those ending with added is
Adding suffixed tags are expecting a boolean which when true will be added
or removed based on the tag used.
But onTagAdded/Removed already adds the tag, before the function is called hence we can do some additional logic or else strip the ng-model of the added value or add back the removed value(not very easy).
Check the below JSFiddle to see the four attributes in action here
I have made a custom service to supply the data, so the final answer to your question will be to use the appropriate attribute (onTagAdding, onTagAdded, onTagRemoving, onTagRemoved) based on your usecase. From the above code, I think we need not write onTagAdded, onTagRemoved since its done automatically.

how do I take value from this $scope

so I have this code in my chatting application, its for send message to the partner.
$scope.messages = {
from : $scope.datauser['data']['_id'],
fromname : $scope.datauser['data']['nama'],
to : $scope.tmpuserid,
message : $scope.tmp['sendmessage'],
time : moment()
};
I want to add text-to-speech features in my application, the question is how I take the value from $scope.messages but just the message because if I just write $scope.messages, TTS will read all data from from until time
Not sure exactly what you want, but it would be something like:
<div ng-repeat="message in messages">
<p>{{message.message}}</p>
</div>
EDIT: This answer is for iterating through an array of messages.
If it were just one messages object it would be:
<p>{{messages.message}}</p>
Maybe I'm missing something in your question, but if all you want to extract just the message from the messages $scope object you would use JS object dot notation e.g.
var justMessage = $scope.messages.message;
// justMessage = $scope.tmp['send message'];
// OR parse an array
var myPartnerMessages = [];
angular.forEach($scope.messages, function(msg, key) {
this.push(msg.message);
}, myPartnerMessages);
You can get the value from $scope as follows:
View.html
<div ng repeat="item in messages">
<div>{{item.message}}</div>
</div>
You just call the property as $scope.messages.message. Or since you already had it on another scope variable, you can call it as $scope.tmp['sendmessage'].
If you are trying to access from the HTML side, you would use it as this:
<p>{{messages.message}}</p>
Not exactly sure if this is what you need from reading your question, though.
if it is a single object not an array if is an array you should use ng-repeat
On js end you can get it by
$scope.messages.message
On html end you can get it by
{{messages.message}}

Strange bug with ng-repeat and filter

I'm using NodeJS, ANgularJS, and MongoDB with mongoose
Here is my model :
var PostSchema = new mongoose.Schema({
nomReseau : String,
corps : String,
etat : String,
section : String
});
I got a function that change the attribute etat:
$scope.passer = function(index){
var post = $scope.posts[index];
post.etat = "enCours";
Posts.update({id: post._id}, post);
$scope.editing[index] = false;
}
I'm using a ng-repeat for show object in my database :
<ul>
<li ng-repeat="post in posts ">
<p>
<a ng-show="!editing[$index]" href="#/{{post._id}}">{{post.corps}}</a>
</p>
<button ng-show="!editing[$index]" ng-click="passer($index)">Passer</button>
</li>
</ul>
I can see all post in my database and when I click on the button this works perfectly the attribute etat change and all is fine.
But when I add a filter in the ng-repeat like this :
<li ng-repeat="post in posts | filter:{ etat:'aTraiter'} ">
The filter works great I have all post with the attribute etat:'aTraiter'
But if I click on my previous button and change the attribute etat nothing change and I try with other functions they all work wihout the filter but when I put it nothing work.
The problem is that $index will change if less data is shown (because you're filtering). you could use directly post variable
ng-click="passer(post)"
and your function should be something like
$scope.passer = function(post){
post.etat = "enCours";
Posts.update({id: post._id}, post);
var index = $scope.posts.findIndex(function(p) { /* comparison to get original index */ }); /* keep in mind findIndex is not supported on IE, you might want to use filter or for loop instead) */
$scope.editing[index] = false;
}
you could handle editing in the post variable directly. So in your passer function you can do this
post.editing = false;
and in your view
ng-show="!post.editing"
this way you won't use $index and you will prevent all issues with being updated by filters
There are bugs in AngularJS v1.4 where in certain situations the ng-repeat breaks. I upgraded to v1.6 and it went away.
Do you have any controllers/services that access $scope.editing? If so, you might be setting the $scope.editing[$index] equal a previous state where it wasn't equal to false. You may also want to consider that you are assuming $scope.editing[$index] is going to be a boolean. if it has any other type such as string or number then it will evaluate to true.
Otherwise none of your results have the attribute etat equal to 'aTraiter' so they aren't showing. Have you verified that any of them actually do have etat equal to 'aTraiter'. You might be changing that value somewhere else. Possibly from the Passer function

How to $compile the value when using ng-repeat?

<ul class="alert alert-link alert-info"
data-ng-show="messages">
<li data-ng-repeat="msg in messages" data-ng-bind-html="msg | unsafe"></li>
</ul>
The controller code looks as below:
...
var msg = 'You\'re logged in. The registration must ' +
+ 'be <a href="#" ' +
+ 'data-ng-click="logout(\'/ajax/logout/\', $event)">logout</a> of your profile.';
$scope.messages = [msg];
...
How to $compile a msg, if msg comes from the server?
In general it's a really really terrible idea to compile things in angular directly from your backend. You can usually tell that if you're written the word unsafe in your code, you are putting yourself at risk. Not to mention it's going to be hard to find issues with the code if the code is on some other server/model/database somewhere. You should just return a model you can use from your server.
If you must do this, you'll probably want to create a directive which has something like element.html($compile(msg)(scope)) in your link function.

How to stringify JSON to JavaScript array

My form in the html DOM is a checkbox to click (there can be more than one). The problem occurs in the description string when ever I use an apostrophe, since my list object is single-quote deliniated. This is one of the checkboxes in the form:
<input type="checkbox" id="cbx" name="cbx" value="{'getPic': 'url', 'picsrc': 'http://lh3.ggpht.com/_ZB3cttqooN0/SVmJPfusGWI/AAAAAAAADvA/GuIRgh6eMOI/Grand%20Canyon%201213_121508214.JPG', 'pos': None, 'description': 'Here's what it REALLY looks like at 5:30am! Bring your headlight!'}">
The javascript that reads the values of the checked checkboxes and pushes them into an array (list):
var pylist = [];
for (i=0; i<document.picList.cbx.length; i++) {
if (document.picList.cbx[i].checked) {
pylist.push( document.picList.cbx[i].value );
}
}
var getstr = JSON.stringify(pylist);
The problem is always that getstr at this point has chopped off everthing after the single quote in the description property.
I've tried different ways of escaping it to little avail.
The problem is that the value of the checkbox already is a JSON string. One solution would be to call JSON.parse() on the value:
var pylist = [];
for (i=0; i<document.picList.cbx.length; i++) {
if (document.picList.cbx[i].checked) {
pylist.push( JSON.parse( document.picList.cbx[i].value) );
}
}
var getstr = JSON.stringify(pylist);
I've run into the same issue - we stick json in a hidden field so we don't have to query the server on every page. We replace apostrophes with a "code" before putting into the html - we added a javascript function that replaces the code with an apostrophe.
Really hacky, but it works really well. Of course, we have one place in the code that gets json from the server and one place where javascript needs to parse it - if you find you're repeating the methods throughout your code, your mileage will vary.

Resources