Using ng-init and ng-repeat in the same div - javascript

I'm not sure it is possible to use ng-init and ng-repeat in the same div. I need it to select from the database all comments that have an id of 6.
I'm calling the code here and displaying an array:
< div ng-init="getComments('6')" ng-repeat="comment in comments">{{ comment.message }}< /div>
And this is what the function looks like in the angular file:
$scope.getComments = function(statusid) {
Comment.get(statusid)
.success(function(data) {
$scope.comments = data;
$scope.loading = false;
});
};
And calling the API here:
return {
// get all the comments
get : function(statusid) {
return $http.get('/api/comments' + statusid);
},
Am I missing something simple? I did not include the PHP files as that seems to all be working fine.

Related

AngularJS - run check against elements as they come back

I just followed this
JSFiddle example to create a little search box from an array object in my javascript. Now after some tweaking and research on search.object and filter:search:strict. Now that I have it filtering correctly, I modified a checkbox in the template that is checked upon loading the document and switched on or off based on a custom data attribute in the html that is updated by the json array.
How do I run this check once someone clears the search and the old items show back up again?
In the HTML I have this template
<div ng-repeat="o in objects | filter:search:strict | orderBy:'obj_name'" class="objectContainer">
<h3>{{o.obj_name}}</h3>
<label class="userToggleSwitch" >
<input class="userToggleInput" data-isactive="{{o.obj_isactive}}" type="checkbox">
<div class="slider round"></div>
</label>
</div>
In the JS
angular.element(document).ready(function(){
angular.module('searchApp',[])
.controller('searchCtrl', ['$scope','objHolder',function ($scope,objHolder) {
$scope.search = '';
$scope.objects = [];
$scope.objects = objHolder.getobjects();
}])
// fake service, substitute with your server call ($http)
.factory('objHolder',function(){
var objects = objList;
return {
getobjects : function(){
return objects;
}
};
});
});
The JS that modifies the items on document load is using jquery like this
$(document).ready(function(){
//console.log($('.userToggleInput'));
$.each($('.userToggleInput'), function(){
if($(this).data("isactive") == 1){$(this).attr('checked', true);}
if($(this).data("isactive") == 0){$(this).attr('checked', false);}
})
$('.userToggleInput').click(function(){
if ($(this).attr('checked') == undefined) {
// THIS IS WHERE WE WILL MAKE AN AJAX CALL TO A PHP CLASS
// TO REQUEST IF THE USER CAN BE TURNED ON - DUE TO LIC RESTRICTIONS
$(this).attr('checked',true);
} else {
$(this).attr('checked',false);
}
//console.log($(this).attr('checked'));
});
});
Created JS Fiddle to assist in Helping in this manner

angularjs: how to store the function returning value in one variable . based on ng-repeat

hi i am getting the intrestedid from ng-repeat , i want to call another service and store that data in one variable dynamically , because need send seperate api for getting images.
my html is look like this
<div class="" ng-repeat="item in items" >
<div ng-init="MyPic = getMyprofile(item.interestedTo)">
<img src="{{MyPic}}">
</div>
</div>
My controller is look like this.
$scope.getMyprofile = function(IntrstdId){
appServices.profile( IntrstdId, function(response){
$scope.meDetails = response.data;
})
return $scope.meDetails;
}
My services is look like this.
service.profile= function(userId, callback) {
path = serviceUrl + '/profile/'+ userId;
$http({
method: 'GET',
url: path
}).then(function(data) {
callback(data)
}, function(data) {});
}
but its getting undefined , any issues in this code.
I tried to resolve this by creating some abstract stub, that may be helpful to you. Please review and let me know if issue still arise
HTML
<div ng-repeat ="data_ in parentData track by $index">
<ul>
<li ng-repeat="result in data_.data track by $index" ng-init="counter=increaseCounter();">
<div ng-model="counter"></div>
</ul>
</div>
Controller
// It simply store variable value in scope.counter
$scope.counter = 0;
$scope.increaseCounter = function () {
var cnt = $scope.counter++;
return cnt;
};
//Another way is to call service while update variable vaule
$scope.counter = 0;
$scope.increaseCounter = function () {
var cnt = $scope.counter++;
AppService.updateValue(cnt);
return cnt;
};
$scope.getMyprofile = function(IntrstdId){
appServices.profile( IntrstdId, function(response){
$scope.meDetails = response.data;
})
return $scope.meDetails;
}
I think issue is this function. appService.profile is asyncronize method and before complete it function return $scope.meDetails;
my suggestion is to hardcore some value like in below and see the result. if it is working then you have to change the function accordingly.
$scope.meDetails ='some value';
return $scope.meDetails;
There are several best practice issue along with the async problem.
1.Avoid using ng-init unless you want to re-run the function when you reconstruct the element, for instance ng-if. It is more so when you use ng-repeat without track by, any changes in the data source would re-trigger all ng-init in the children.
Solution: Run them when you init the controller, or as soon as $scope.items is filled.
angular.forEach($scope.items, function(item) {
appServices.profile(item).then(function(data){
item.myPic = data;
});
});
<div class="" ng-repeat="item in items" >
<img src="{{item.myPic}}">
</div>
2.The correct way to wrap a function that returns promise (which $http is) is to return the function itself. You can research more on how to pass the resolved/rejected result around.
// not needed anymore, just to showcase
$scope.getMyprofile = function(IntrstdId){
return appServices.profile( IntrstdId );
}
// same goes with the service function
service.profile= function(userId) {
path = serviceUrl + '/profile/'+ userId;
return $http({
method: 'GET',
url: path
}).then(function(response) {
return response.data;
});
}

Angular ng-repeat scope issue

Nothing in my {{}} are showing in my html file. Can someone please tell me what I am doing wrong. I have no errors in my console.
"GOT DATA" will print in my console, but not show in my file.
The is my html code
<div class="announcements" ng-controller="onBusinessAnnouncementCtrl as announcements">
{{announcements.latest}}
</div>
This is my js code pulling from the server
app.controller('onBusinessAnnouncementCtrl', function($scope, $http) {
$http.get('http://localhost:3000/latest')
.success(function(responses) {
//$scope.latest = responses;
$scope.latest = "GOT DATA";
console.log($scope.latest);
});
});
Because you use the controller as syntac you should apply the variables in your controller to this instead of $scope.
See the same problem in AngularJS Ng-repeat is not working as expected where a repeater was used
below the answer on the previous question:
In your repeater you're looping over announcements.announcements in your controller you set $scope.announcements = response.
Either you change the repeater in ng-repeat="eachAnnouncement in announcements" or change your scope variable to: $scope.announcements = {announcements : response}
Figured it out! For reference:
There is nothing showing in my HTML because there is no value assigned to the controller. To assign "latest" to my controller I have to do this:
app.controller('onBusinessAnnouncementCtrl', function($scope, $http) {
$http.get('http://localhost:3000/latest')
var this = this;
.success(function(responses) {
this.latest = responses;
});
});
<div class="announcements" ng-controller="onBusinessAnnouncementCtrl as announcements">{{announcements.latest}}</div>

Parse JSON without specific element name in AngularJS

I want to parse the JSON response of Country & State from below mentioned URL.
https://gist.githubusercontent.com/mayurah/5f4a6b18b1aa8c26910f/raw/countriesToCities.json
{
"China": [
"Guangzhou",
"Fuzhou",
"Beijing",
"Baotou",
"Hohhot",
"Guiyang",
"Yinchuan",
"Nanjing",
"Changzhou",
"Chuzhou",
"Hefei",
"Jinan",
"Qingdao",
"Harbin",
"Zhaodong",
"Taiyuan",
"Xi'an",
.
.
.
}
]
I want the result as,
Guangzhou, China
Taiyuan, China
I am using AngularJS, Following is a piece of code of my controllers.js file.
var
apiUrl = {
countryStateList: 'https://gist.githubusercontent.com/mayurah/5f4a6b18b1aa8c26910f/raw/countriesToCities.json'
};
countryData.controller('countryDataCtrl', ['$scope', '$http', function($scope, $http) {
$http.get(apiUrl.countryStateList).success(function(data) {
// console.log(data);
$scope.countryStateList = data;
});
}]);
And, in my HTML file, code is something like this,
<ul ng-repeat="country in countryStateList">
<li>{{ STATE_NAME, COUNTRY_NAME }}</li>
</ul>
STATE_NAME & COUNTRY_NAME are just for in display information. Both must be replaced with Angular code.
The problem is JSON element names are itself country names. Can someone tell me how to parse the same in AngularJS/Javascript.
You could start by parsing the whole JSON:
var jsonObject = JSON.parse(RAW_JSON_STING);
var newJsonObject = [];
// Loop through it
for (var interator in jsonObject)
{
for (var it = 0; it < iterator.length; it++)
{
newJsonObject.push(iterator[it] + ", " + iterator);
}
}
No guarantee the code above will work as intended.
Ng-repeat will not be useful in your case. This would be possible using directive.
<datalist id="stateCountry">
<custom-datalist-option data-array="countryStateList"></custom-datalist-option>
</datalist>
Link a directive function and create an option using using it.
Here is the Update Fiddle
Hope this will help you.

Rendering unicode-utf-8 turkish characters with angular-js

Characters from a binded JSON text, Turkish the letters are shown with wrong encoding for eg. Özlem Güzelharcan which shall look like "özlem güzelharcan". I added <meta characters="utf-8"> in the head still no solution and there was no problem with laravel blade views.
If necessary this is how I get and use data:
view:
<div class="comment" ng-hide="loading" ng-repeat="comment in comments">
Comment #{{ comment.id }} </h3> <p>{{comment.title}}</p>
{{comment.author_id}} / {{comment.author.name}}
Services:
// public/js/services/commentService.js
angular.module('commentService', [])
.factory('Comment', function($http) {
var data = {
// get all the comments
get : function() {
return $http.get('/api/comments/');
}
}
console.log(data);
return data;
});
//controller (shortly)
.controller('mainController', function($scope, $http, Comment) {
// object to hold all the data for the new comment form
$scope.commentData = {};
// loading variable to show the spinning loading icon
$scope.loading = true;
// get all the comments first and bind it to the $scope.comments object
// use the function we created in our service
// GET ALL COMMENTS ====================================================
Comment.get()
.success(function(data) {
$scope.comments = data;
$scope.loading = false;
});
});
Which method is used to clean characters with AngularJS?
Thanks
Eventually, after trying many things, I discovered that you have to use ng-bind-html or ng-bind-html-unsafe (with ngSanitize) to get the correct encoding. Here is how it works in my view:
Comment #<span ng-bind-template="{{comment.id}}"></span> </h3>
<span ng-bind-html="comment.title "></span>
<p><div ng-bind-html="comment.content | truncate:25"></div></p>

Categories

Resources