I need some help about toggling ng-src between for example: image.jpg and image-active.jpg, but I have some issues because I need to active that with AngularJS.
This is the scenario: I called an API data from swagger and use ng-repeat to display images in html.
HTML
<div class="input-group interests-list">
<div class="checkbox" ng-repeat="interest in interests">
<label>
<div class="interest-icon">
<img src="{{interest.iconUrl}}" ng-click="changeImage()">
</div>
<input style="display: none;" type="checkbox" value="{{interest.name}}">
{{interest.name}}
</label>
</div>
</div>
Service
this.getInterests = function () {
var deferred = $q.defer();
var req = {
method: 'get',
url: 'http://customdealwebapi20180125110644.azurewebsites.net/api/Interests'
}
$http(req).then(function (response) {
deferred.resolve(response.data);
}, function (err) {
console.log(err)
});
return deferred.promise;
}
Controller
TestService.getInterests().then(function (data) {
$scope.interests = data;
});
and everything works fine
Now I want to achieve when someone click on the image, ng-src should be changed to image-active.jpg, and on the next click image should be changed to default value (image.jpg)
I know how to achieve through jQuery, like this
$(".interests-list .checkbox label input[type='checkbox']").change(function () {
var selectedIcon = $(this).val();
if (this.checked) {
console.log($(this).prev())
$(this).prev().find("img").attr("src", "assets/img/home/icons/" + selectedIcon + "-active.png");
} else {
$(this).prev().find("img").attr("src", "assets/img/home/icons/" + selectedIcon + ".png");
}
});
Thank you
You can either use ng-show
<div class="checkbox" ng-repeat="interest in interests" ng-init="interest.active = false">
<label>
<div class="interest-icon">
<img ng-show="interest.active == true" src="active.png" ng-click="interest.active = !interest.active">
<img ng-show="interest.active == false" src="other.png" ng-click="interest.active = !interest.active">
</div>
</label>
</div>
or you can pass interest to your click function and set image src in your controller
<img src="{{interest.iconUrl}}" ng-click="changeImage(interest)">
$scope.changeImage = function(interest){
if(checked)
interest.iconUrl = "active.png";
else
interest.iconUrl = "other.png";
}
Related
I have a textarea that relies upon a dropdown menu to populate. When the dropdown is changed, a file is pulled and the contents are loaded to the textarea.
While the textarea is loading, it just says [object Object]. I'd like it to be a bit nicer than that. Something like 'Loading...'.
I cant find away to specifically do this with a textarea though.
Another wrench in the wheel is that the Save functionality actually relies upon the value of the text area to save, so I cant just alter the content of the text area to display 'Saving...' otherwise the content that is written to the file is just 'Saving...'.
Here is the code:
View
<div id="Options" class="panel-collapse collapse">
<div class="panel-body">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon input-sm">Config Select</span>
<select ng-change="update()" ng-model="configFileName" class="form-control input-sm">
<option>--</option>
<option ng-repeat="conf in configList" value="{{conf.name}}">{{conf.name}}</option>
</select>
</div>
</div>
<div class="form-group">
<div class="input-group">
<td style="padding-bottom: .5em;" class="text-muted">Config File</td><br />
<textarea id="textareaEdit" rows="20" cols="46" ng-model="configFileContent"></textarea>
<input type="button" ng-click="updateConfig()" style="width: 90px;" value="Save"></button>
</div>
</div>
</div>
</div>
JS
$scope.update = (function(param) {
$scope.configFileContent = 'Loading...';
$scope.configFileContent = $api.request({
module: 'Radius',
action: 'getConfigFileContent',
method: 'POST',
data: $scope.configFileName
}, function(response) {
$timeout(function() {
console.log('got it');
$scope.configFileContent = response.confFileContent;
}, 2000);
});
});
$scope.updateConfig = (function(param) {
var data = [$scope.configFileName, $scope.configFileContent];
var json = JSON.stringify(data);
$scope.configFileContent = $api.request({
module: 'Radius',
action: 'saveConfigFileContent',
method: 'POST',
data: json
}, function(response) {
$timeout(function() {
console.log('Saved!');
$scope.update();
}, 2000);
});
});
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope, $timeout) {
$scope.update = function() {
if ($scope.selectedData === '') {
$scope.someData = '';
return;
}
// do http response
var data = 'dummy file text from server';
$scope.xhr = false;
$scope.msg = 'loading...';
// simulating fetch request
$timeout(function() {
$scope.xhr = true;
$scope.content = data;
}, 3000);
}
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<select ng-model="selectedData" ng-change="update()">
<option selected="selected" value="">Select data</option>
<option value="foo">Fetch my data</option>
</select>
<br><br><br>
<textarea rows="5" cols="20" ng-model="someData" ng-value="xhr === false ? msg : content">
</textarea>
</div>
You can use a scope variable to detect the completion of promise request of xhr and simulate a loading... message.
As for save, i recommend not to use such approach of displaying message inside textarea and instead create another directive/component to detect the loading and saving request completion which is reusable and separates business logic keeping controller thin.
fellas!
I'm trying to validate a text area upon clicking a link. Thing is, It's not coming inside a form. And when a user clicks a link, content entered in the text area should be posted (saved to database).
I wrote a validation for that. And unfortunately, it's not working and I'm able to make blank posts. I'm trying to prevent blank post posting. I have recreated the form and the controller in a fiddle. Link I'll provide down. but before that, take a look at my html and js code.
HTML
<div ng-app="myApp" ng-controller="myMap">
<div class="post-textarea" ng-class="{ 'has-error': vm.currentPost.content.$dirty && vm.currentPost.content.$error.required }">
<textarea class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
<a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Clik to Post and validate</a>
</div>
</div>
JavaScript
angular.module('myApp', [])
.factory('myService', function($http) {
var baseUrl = 'api/';
return {
postCurrentPost: function(newPost) {
var dataPost = {
newPost: newPost
};
return $http({
method: 'post',
url: baseUrl + 'postCurrentPost',
data: dataPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
}
};
})
.controller('myMap', function(myService, $http, $scope) {
var vm = this;
var userObject;
// Add a post
vm.addPost = function(newPost, isValid) {
if (isValid) {
var currentPost = vm.currentPost;
currentPost.content = ""; //clear post textarea
myService.postCurrentPost(newPost).success(function(data) {
vm.posts = data;
});
} else {
alert('Validation not working');
}
};
//Check validation
$scope.getError = function(error, name) {
if (angular.isDefined(error)) {
if (error.required && name == 'vm.currentPost.content') {
return "This field is required";
}
}
}
});
And here's a FIDDLE.
Name of the form input element should be used instead of model value.
https://docs.angularjs.org/api/ng/directive/form
<div ng-app="myApp" ng-controller="myMap">
<form name="formContent">
<div class="post-textarea" ng-class="{ 'has-error': formContent.content.$dirty && formContent.content.$error.required }">
<textarea name='content' class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
<a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Clik to Post and validate</a>
</div>
</form>
Content is dirty: {{formContent.content.$dirty}}
<br>
Content has required: {{formContent.content.$error.required}}
</div>
I'm very new to angular so I may be going about this all wrong but here goes. I have a form
<form name="search_form" novalidate ng-submit="searchForm(search_form.$valid)" >
<div class="maincontainer">
<div class="formcontainer">What to eat?</div>
<div class="formcontainer"><input type="text" name="food_type" ng-model="food_type" placeholder="Enter a search term" required></div>
<div class="formcontainer">Where to look?</div>
<div class="formcontainer"> <input type="text" name="cityname" ng-model="trader.cityname" value="cityname" googleplace="" placeholder="Enter a location" required>
</div>
<div class="formcontainer">
<button type="submit" class="btn-main2" >Submit</button>
</div>
</form>
that when I submit I want to grab the results based on the location I get from google and display them in a new view
myControllers.controller('SearchCtrl',['$scope','Search','$location', function ($scope,Search,$location) {
$scope.setSearchLocation = function(place){
$scope.lat = place.geometry.location.lat();
$scope.lng = place.geometry.location.lng();
}
$scope.searchForm = function() {
// check to make sure the form is valid
if (!$scope.search_form.$valid) {
alert('Please fill out all fields');
}
else{
$scope.results = Search.do_search($scope.lat,$scope.lng);
$location.path('search-results');
}
};
}])
.directive('googleplace', function() {
return {
require : 'ngModel',
link : function(scope, element, attrs, model) {
var options = {
types : [],
};
scope.gPlace = new google.maps.places.Autocomplete(element[0],options);
google.maps.event.addListener(scope.gPlace, 'place_changed',function() {
var place = scope.gPlace.getPlace();
scope.setSearchLocation(place);
scope.$apply(function() {
model.$setViewValue(element.val());
});
});
},
};
});
everything works as expected except the view does not update in the results view. If I set the $scope.results out side the searchForm() function everything renders properly. I realize this is because it exists before the page renders, just saying that part works.
when I try $scope.$apply() it says already in progress
<div id="results-container" ng-repeat="result in results">
<div id="picbox"><img src="../images/test.jpg" alt="" "/></div>
<div id="addressinfo">
<h4>John's Restaurant </h4>
<p>123 York Street, Toronto ON <br>
<span id="type">#
Burgers, #Poutine</span></p>
</div>
<div id="location">4.2m<br>
<img src="../images/heart.png" width="86" height="76" alt=""/><br>
</div>
</div>
</div>
When you call $location.path(...), $scope object of controller is always initialized.
My suggestion is ...
write the element of div#results-container on the same template where form[name=search_form] exists.
remove $location.path('search-results');
I hope this could help you.
Building an cross-platform hybrid app using Parse.com, AngularJS using the Ionic Framework. The user creation and querying works fine when using the simple parse.com code from the docs.
However I have been trying to put the query into a AngularJS service, so that it can be accesses and I can do a ng-repeat to display the returned results in a list.
The code put in place so far is this:
View (search.html):
<div class="row">
<div class="col col-75">
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" placeholder="Search" ng-model="search.queryvalue">
</label>
</div>
<div class="col">
<button class="button button-calm" ng-click="searchnow()">Search</button>
</div>
</div>
<ion-list>
<ion-item class="item-avatar" type="item-text-wrap" ng-repeat="user in users">
<img ng-src="{{userpic}}.png">
<h2>{{user.id}}</h2>
<p>{{user.get('location')}}</p>
</ion-item>
</ion-list>
Controller:
.controller('SearchCtrl', function($scope, $state, $rootScope, parseQueryFactory) {
$scope.search = {};
$scope.users = {};
$scope.searchnow = function () {
$scope.users = parseQueryFactory.searchUsers($scope.search.queryvalue);
};
})
Services:
.factory('parseQueryFactory', function($http) {
var query = new Parse.Query(Parse.User);
var people = {};
return {
searchUsers: function(searchVal){
query.startsWith("username", searchVal); // Search username
query.limit(20);
return query.find({
success: function(people) {
/*var objects = {};
for (var i = 0; i < people.length; i++) {
var object = people[i];
objects = objects + object;
}
console.log(people);
return objects;*/
},
error: function(error) {
return error;
}
});
}
}
})
I have tried a few ways to make this work (using sources like the ionic forum, stackoverflow and Google in general), but I am new to angular and not sure how to go about doing this.
The only thing that works is by putting the following code in the controller (but then I cannot use ng-repeat):
$scope.searchnow = function () {
var queryvalue = $scope.user.queryvalue;
userquery.startsWith("username", queryvalue); // Search username
userquery.limit(20);
userquery.find({
success: function(people) {
for (var i = 0; i < people.length; i++) {
var object = people[i];
console.log("ID: " + object.id + ', username: ' + object.get('username'));
}
}, error: function(error) {
console.log("error");
}
});
};
Has anyone implemented such a service for parse.com?
I have looked around and tried implementations from various people, but nothing seems to work in a way that returns a service like response from which ng-repeat comands can be done.
I believe this might help.
Services:
app.factory('Presentation', function($q) {
var Presentation = Parse.Object.extend(Parse.User, {
// Instance methods
}, {
// Class methods
listByUser : function() {
var defer = $q.defer();
var query = new Parse.Query(this);
query.startsWith("username", searchVal); // Search username
query.limit(20);
query.find({
success : function(aPresentations) {
defer.resolve(aPresentations);
},
error : function(aError) {
defer.reject(aError);
}
});
return defer.promise;
}
});
// Properties
Presentation.prototype.__defineGetter__("location", function() {
return this.get("location");
});
Presentation.prototype.__defineGetter__("pic", function() {
var pic = this.get("pic");
if (pic ==null){
pic = 'img/default.png';
return pic;
}
return pic.url();
});
return Presentation; });
Controller:
app.controller('userController', function( Presentation){
user = this;
Presentation.listByUser().then(function(aPresentations) {
user.list = aPresentations;
}, function(aError) {
// Something went wrong, handle the error
});
});
html:
<div class="row">
<div class="col col-75">
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" placeholder="Search" ng-model="search.queryvalue">
</label>
</div>
<div class="col">
<button class="button button-calm" ng- click="searchnow()">Search</button>
</div>
</div>
<ion-list>
<ion-item class="item-avatar" type="item-text-wrap" ng-repeat="user in users">
<img ng-src="{{user.pic}}">
<h2>{{user.id}}</h2>
<p>{{user.location}}</p>
</ion-item>
</ion-list>
For further reading you can check out 5 Tips for using parse with angularjs by slidebean.
I have posted earlier this post with the choice of not providing all my code. But now im stuck since with the same problem so I give it a change with providing all my code.
I know its not easy to debug when the code is huge so I will try to explain precisely the problem.
Actually the problem is described in my precedent post so please read it and look at the code that is a simplification of this one.
But basically the problem is : I want to access $scope.data.comments from the $scope.deleteComment() function
As you see the code below you will notice that I have to add ng-controller="CommentController" twice for this to work.
If someone could explain why.. that would be great but I guess that is another question.
Thanks in advance for your help.
MAIN HTML
<div ng-init="loadComments('${params.username}', '${params.urlname}' )" ng-controller="CommentController">
<div ng-repeat="comments in data.comments" >
<div sdcomment param="comments" ></div>
</div>
</div>
APP
var soundshareApp = angular.module('soundshareApp', ['ngCookies']);
DIRECTIVES
soundshareApp.directive('sdcomment', ['$cookies', function($cookies){
var discussionId = null;
var found = false;
var username = $cookies.soundshare_username;
return {
restrict:'A',
scope: {
commentData: '=param'
},
templateUrl: '/js/views/comment/templates/commentList.html',
link : function(scope, element, attrs, controller) {
scope.$watch(element.children(), function(){
var children = element.children();
for(var i=0; i<children.length; i++){
if(children[i].nodeType !== 8){ //pas un commentaire <!-- -->
if( !found ){
found = true;
discussionId == scope.commentData.discussionId
}else if(found && discussionId == scope.commentData.discussionId){
angular.element(children[i]).removeClass('message-content');
angular.element(children[i]).addClass('answer-message-content');
}
if(found && discussionId != scope.commentData.discussionId){
discussionId = scope.commentData.discussionId
}
if(username == scope.commentData.username){
element.parent().bind('mouseover', function() {
// $(".delete-comment-button").show()
element.parent().find("span.delete-comment-button:first").attr('style', 'display: block !important');
});
element.parent().bind('mouseleave', function() {
element.parent().find("span.delete-comment-button:first").attr('style', 'none: block !important');
});
}
}
}
});
}
}
}]);
TEMPLATE
<div class="message-wrapper" ng-controller="CommentController">
<div class='message-content' ng-click="state.show = !state.show; setUsername(commentData.username)">
<img class='message-vignette' ng-src='{{commentData.avatarUrl}}'/>
<div class='message-username'>{{commentData.username}}</div>
<div class='project-message'>{{commentData.comment}}</div>
<div class='message-date'>{{commentData.dateCreated | date:'dd.MM.yyyy # hh:mm:ss' }}</div>
<div class="clearfix"></div>
</div>
<div ng-repeat="answer in answers" class="answer-message-content" >
<div class='message-content' ng-click="state.show = !state.show">
<img class='message-vignette' ng-src='{{answer.avatarUrl}}'/>
<div class='message-username'>{{answer.username}}</div>
<div class='project-message'> {{answer.comment}}</div>
<div class='message-date'>{{answer.dateCreated | date:'MM/dd/yyyy # h:mma' }}</div>
<div class="clearfix"></div>
</div>
</div>
<div class="add-comment-content show-hide" ng-show="state.show" >
<img class='message-vignette answer-message-vignette' ng-src='{{commentData.currentUserAvatarUrl}}'>
<div class="">
<form ng-submit="addComment(commentData)" id="commentForm-{{commentData.projectId}}">
<input id="input-comment-{{commentData.projectId}}" type="text" maxlength="" autofocus="autofocus" name="comment" placeholder="Write a comment..." ng-model="commentData.msg">
<input type="hidden" name="discussionId" value="{{commentData.discussionId}}" >
<input type="hidden" name="projectId" value="{{commentData.projectId}}" >
</form>
</div>
</div>
<span ng-click="deleteComment(commentData)" class="btn btn-default btn-xs delete-comment-button"><i class="icon-trash"></i></span>
</div>
CONTROLLER
'use strict';
soundshareApp.controller('CommentController', function($scope, $http) {
$scope.data = { comments : [] }
$scope.answers = [];
$scope.state = {}
$scope.project = { id : [] }
$scope.username = null;
$scope.loadComments = function(userName, urlName){
$http({
url: '/comment/by_project_id',
method: "GET",
params:
{
username: userName,
urlname: urlName
}
}).success(function(data) {
$scope.data.comments = data;
console.log($scope.data.comments);//WORKING
});;
}
$scope.addComment = function(commentData){
if("undefined" != commentData.msg){
commentData.msg = "#" + $scope.username + ": " + commentData.msg;
$http({
method : "POST",
url : "/comment/addAnswer",
params:
{
comment: commentData.msg,
discussionId: commentData.discussionId,
projectId:commentData.projectId
}
}).success(function(data){
$scope.answers.push(data);
$('.show-hide').hide();
$scope.commentData.msg = '';
});
}
}
$scope.setUsername = function(username){
$scope.username = username;
}
$scope.deleteComment = function ( comment ) {
console.log($scope.data.comments);//NOT WORKING
};
});