Different template on angular - angularjs

On my HTML code I want to display either a gallery of images or just one image ... The templates are different:
if (mode = 0) {
<div data-ng-controller="ImageController" class="gallery">
<div data-ng-repeat='image in model.images'>
<img data-ng-src="image.Url"/>
// Some more code
</div>
</div>
} else {
<div data-ng-controller="ImageController" class="image">
<img src="data-ng-src="{image.Url}" />
// Other code
</div>
}
On angular controller I have the following:
application.controller('ImageController', function ImageController($scope, ImageService) {
$scope.model = {
images: []
}
var init = function () {
ImageService.GetList($scope.model.pages.instagram)
.success(function (data, status, headers, config) {
$scope.model.images = $scope.model.images.concat(data.Images);
})
.error(function (data, status, headers, config) { });
}
How to modify the controller to display either a list of images or one single image?

HTML
<script type="text/javascript">
window.isMultiple = '#RazorIsMultiple';
</script>
<div data-ng-controller="ImageController" class="gallery">
<!--<input type="hidden" data-ng-model="mode.isMultiple" value="#RazorIsMultiple"/>-->
<div data-ng-if="mode.isMultiple" data-ng-repeat='image in model.images'>
<img data-ng-src="image.Url"/>
// Some more code
</div>
<img data-ng-if="!mode.isMultiple" src="data-ng-src="{image.Url}" />
// Other code
</div>
and in your controller, add something like that :
during init of the controller
$scope.mode = {};
//$scope.$watch('mode.isMultiple', function(newVal, oldVal){
// //insert your logic here
//});
$scope.mode.isMultiple = window.isMultiple;

Related

AngularJS toggle ng source value on click

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";
}

Cannot extract all the "feed" information(Pictures) from facebook graph API

I am trying to extract information through facebook API into my ionic app. It shows the messages and dates correctly into my app but no images! I have uploaded the code and demo pictures in here.
Code:
.controller('FeedCtrl', function ($scope, $stateParams, OpenFB, $ionicLoading) {
$scope.show = function () {
$scope.loading = $ionicLoading.show({
content: 'Loading User Feed(s)...'
});
};
$scope.hide = function () {
$scope.loading.hide();
};
function loadFeed() {
$scope.show();
OpenFB.get('/me/feed', {
limit: 30
})
.success(function (result) {
$scope.hide();
$scope.items = result.data;
// Used with pull-to-refresh
$scope.$broadcast('scroll.refreshComplete');
})
.error(function (data) {
$scope.hide();
alert(data.error.message);
});
}
**[<!---ionic---->][1]**
<div ng-repeat="item in items" class="list card">
<div class="item item-avatar">
<img src="https://graph.facebook.com/{{ item.from.id }}/picture" />
<h2>{{item.name}}</h2>
<p>{{item.created_time | date:'MMM d, y h:mma'}}</p>
</div>
<div class="item item-body">
<p ng-if="item.story">{{item.story}}</p>
<p>{{item.message}}</p>
<h2>{{item.from.id}}</h2>
<img ng-if="item.picture" ng-src="{{item.picture}}" />
</div>
</div>
And

Function automatically called in some condition

I have code like this:
<div class="row"
ng-repeat="x in companies|orderBy:'id' ">
<div class="col left" >
<button ng-click="viewPublicId(x.id)">{{x.companyname}}</button>
</div>
<div class="col left">
{{x.address}}
</div>
<div class="col left">
{{x.telephone}}
</div>
</div>
What I want to do is add a check: when companies.size=1, function viewPublicId is automatically called. How can I achieve that? Thanks.
updated: viewPublicId function:
$scope.viewPublicId = function viewPublicId(companyid) {
var url = "http://7cf8d64c.tunnel.mobi/yii2-basic/web/index.php?r=restpublic/view&companyid=" + companyid;
console.log("debug", url);
$http.get(url)
.success(function (response)
{
console.log("debug PublicId",response);
if(response.length==33)
$scope.publicids = null;
else
$scope.publicids = response;
})
.error(function (response)
{
console.log("debug PublicId",response);
$scope.publicids = null;
});
$state.go('tabs.publicidlist');
}
In you controller:
if ($scope.companies.length === 1) {
$scope.viewPublicId();
}
If your companies could be changed dynamically, and you need to call the function everytime it changes, use $watch:
$scope.$watch('companies', function () {
if ($scope.companies.length === 1) {
$scope.viewPublicId();
}
}, true);

Uploading Multiple files from Angular JS to SQL DB using MVC Web API

<!DOCTYPE html>
<html ng-app="messageBoardApp" class="page-header">
<head>
<title></title>
<link href="../libs/bootstrap.min.css" rel="stylesheet" />
<!--<script src="Scripts/angular-route.min.js"></script>-->
<script src="../libs/angular.min.js"></script>
<script src="../libs/angular-file-upload.min.js"></script>
<script src="../libs/console-sham.min.js"></script>
<script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
<script src="MessageBoardModule.js"></script>
<script src="MessageBoardController.js"></script>
<script src="MessageBoardService.js"></script>
</head>
<body ng-controller="messageBoardController" class="container">
<div>
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="titleText" ng-model="message.title" class="form-control" />
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="contentText" ng-model="message.content" rows="5" cols="40" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="file">File</label>
<input type="file" nv-file-select="" uploader="uploader" multiple>
</div>
<div class="form-group">
<label for="fileList">These are your selected files</label>
<br/>
<ul>
<select name="files" ng-model="selectedFile" ng-options="option.file.name for option in uploader.queue" size="4" class="form-control"></select>
</ul>
</div>
<br/>
<div class="col-sm-offset-0 col-sm-6">
<input type="button" value="Remove File" ng-click="remove()" />
<button ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">Remove all</button>
</div>
<br/>
<br/>
<br/>
<div class="col-sm-offset-4 col-sm-6">
<button ng-click="uploader.uploadAll()">Upload All</button>
<!--<input type="submit" value="Add Message" ng-click="submitForm()"/>-->
<input type="button" value="Exit" ng-click="Close()" />
</div>
</form>
</div>
</body>
</html>
Controller:
messageBoardApp.controller('messageBoardController', ['$scope', 'FileUploader', 'MessageBoardService',
function ($scope, FileUploader, MessageBoardService) {
var uploader = $scope.uploader = new FileUploader({});
$scope.remove = function (selectedItem) {
$scope.uploader.queue.splice(uploader.queue.indexOf(selectedItem), 1);
};
//$scope.message=messageBoardService.SaveMessage();
$scope.submitForm = function () {
alert("Controller");
var message = $scope.message;
MessageBoardService.SaveMessage(message);
//MessageBoardService.SaveMessage($scope.message);
};
// FILTERS
uploader.filters.push({
name: 'customFilter',
fn: function (item /*{File|FileLikeObject}*/, options) {
return this.queue.length < 10;
}
});
// CALLBACKS
uploader.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {
console.info('onWhenAddingFileFailed', item, filter, options);
};
uploader.onAfterAddingFile = function (fileItem) {
console.info('onAfterAddingFile', fileItem);
};
uploader.onAfterAddingAll = function (addedFileItems) {
console.info('onAfterAddingAll', addedFileItems);
};
uploader.onBeforeUploadItem = function (item) {
console.info('onBeforeUploadItem', item);
};
uploader.onProgressItem = function (fileItem, progress) {
console.info('onProgressItem', fileItem, progress);
};
uploader.onProgressAll = function (progress) {
console.info('onProgressAll', progress);
};
uploader.onSuccessItem = function (fileItem, response, status, headers) {
console.info('onSuccessItem', fileItem, response, status, headers);
};
uploader.onErrorItem = function (fileItem, response, status, headers) {
console.info('onErrorItem', fileItem, response, status, headers);
};
uploader.onCancelItem = function (fileItem, response, status, headers) {
console.info('onCancelItem', fileItem, response, status, headers);
};
uploader.onCompleteItem = function (fileItem, response, status, headers) {
console.info('onCompleteItem', fileItem, response, status, headers);
};
uploader.onCompleteAll = function () {
console.info('onCompleteAll');
};
console.info('uploader', uploader);
// -------------------------------
}]);
Service:
messageBoardApp.factory('MessageBoardService', function () {
var SaveMessage = function (newMessage) {
alert(newMessage.content);
alert(newMessage.title);
return true;
};
return {
SaveMessage: SaveMessage
};
});
Module:
var messageBoardApp = angular.module("messageBoardApp", ['angularFileUpload']);
Am using below file-upload js from this link
https://github.com/nervgh/angular-file-upload/
I understand all the files which i have selected are in queue. Am not sure how to pass this files(more than 1) to .net mvc wep api call controller and then pass value to SQL DB.
Am stuck up with passing all the form values to service and then to wep api controller.
When you initialize your FileUploader you have to say to which url you would like to post your files. For example:
var uploader = $scope.uploader = new fileUploader({
url: window.location.protocol + "//" + window.location.host + window.location.pathname + "/api/Upload/UploadFile"
});

ng-click ng-keypress passing form data not working

Im trying to send data from user input to display on the screen when button click.
The problem is that if i click on the button it simply passes to the next value without gathering the information and displaying in the screen. If i press ENTER it works how it should. i have searched all over internet several examples but simply couldnt get it to work. im using at the moment :
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
full html:
<div class="boxContent col-md-12">
<h1>{{lang.sec101.h1}}</h1>
<div class="col-md-12 lineBorder noPad" >
<div class="box1">
<p>
{{lang.sec101.title}}
</p>
</div>
<!-- dynamic form -->
<div class="col-md-12 borderBox boxLeft bg_box">
<form novalidate name="addForm">
<div class="boxLeft" ng-show="Question != ''">
<div ng-show="Question.infotip != 'yes'">
<h1 class="heading_left">{{Question.ask}}</h1>
</div>
<div ng-show="Question.infotip == 'yes'">
<h1 class="heading_left info">{{Question.ask}}
<span class="infotip yourData" tooltip-placement="top" tooltip-trigger="click" tooltip="{{Question.infotipText}}"></span>
</h1>
</div>
</div>
<div class="boxRight" ng-show="Question != ''">
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
</div>
<div class="boxRejestracjaInput">
<!-- <div id="legg-select" ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</div> -->
<div class="newSelect">
<label ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</label>
</div>
<input
ng-if="Question.type === 'text'"
type="{{Question.type}}"
name="institutionName"
class="inputName"
value="{{Question.value}}"
ng-model="value"
ng-minlength="{{Question.min}}"
ng-maxlength="{{Question.max}}"
ng-keypress="enter($event,value)"
placeholder="{{Question.placeholder}}"
ng-pattern="{{Question.pattern}}" />
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.minlength || addForm.institutionName.$error.maxlength">
Minimum {{Question.min}} znaków
</div> -->
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.maxlength">
Max {{Question.max}} znaków
</div> -->
<div class="custom-error institution" ng-show="addForm.institutionName.$error.pattern || addForm.institutionName.$error.maxlength || addForm.institutionName.$error.minlength">
{{Question.copy}}
</div>
</div>
</form>
</div>
<p>
{{lang.sec101.title2}}
</p>
<a href="rejestracja_10edit.html" class="btn btn-lg btn-default bt_edit" type="button">
{{lang.sec101.title3}}<span class="btn_bg_img"></span>
</a>
</div>
<div class="col-md-12 noPad" ng-repeat="sek in formOut">
<h3 class="daneHeading">{{sek.name}}</h3>
<div class="row">
<div class="col-md-12" >
<div class="col-md-4 col-sm-6 boxContent3 boxes" ng-repeat="row in sek.data">
<span class="leftBoxContrnt">{{row.shortAsk}}</h4></span>
<h4 class="rightBoxContrnt">{{row.value}}</h4>
</div>
</div>
</div>
</div>
<!-- <div class="row col-md-12" >
<h3 class="daneHeading">Hasło</h3>
</div>
<div class="row">
<div class="col-md-12 " >
<div class="col-md-4 col-sm-6 boxContent3">
<span class="leftBoxContrnt">Test</h4></span><span class="blueTxt"> *</span>
<h4 class="rightBoxContrnt">Test</h4>
</div>
</div>
</div> -->
</div>
my controller:
var app = angular.module('app', ['ngAnimate', 'ngCookies', 'ui.bootstrap', 'ngSanitize', 'nya.bootstrap.select', 'jackrabbitsgroup.angular-slider-directive']);
// var rej10_Controller = function($scope, $http, $cookieStore, $timeout, limitToFilter) {
app.controller('rej10_Controller', ['$scope', '$http', '$cookieStore', '$sce', '$timeout', 'limitToFilter',
function($scope, $http, $cookieStore, $sce, $timeout, limitToFilter) {
var view = 10,
arr,
data,
counterSection = 0,
counterAsk = 0;
$scope.opts = {};
$scope.slider_id = 'my-slider';
$scope.opts = {
'num_handles': 1,
'user_values': [0, 1],
'slider_min': 0,
'slider_max': 1,
'precision': 0,
};
/* language */
if (!$cookieStore.get('lang'))
$cookieStore.put('lang', 'pl');
var lang = $cookieStore.get('lang');
$scope.language = lang;
$scope.setLang = function(data) {
$cookieStore.put('lang', data);
$http.get('../widoki/json/lang/' + data + '/rej_' + view + '.json').
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn.sekcja[counterSection].data[counterAsk];
console.log($scope.lang);
}).
error(function(data, status, headers, config) {
console.log('error load json');
});
$scope.language = data;
};
/* get language pack */
$http({
method: 'GET',
url: '../widoki/json/lang/' + lang + '/rej_' + view + '.json'
}).
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
$scope.langLen = $scope.lang.formIn.length;
}).error(function(data, status, headers, config) {
console.log('error load json');
});
/* dynamic form */
$scope.enter = function(ev, d) {
if (ev.which == 13) {
$scope.addData(d);
}
};
$scope.addData = function(data) {
var newData = {};
/* latamy po id sekcji i po id pytania */
if (!$scope.formOut) {
$scope.formOut = [];
}
/* budowanie modelu danych wychodzcych */
newData = {
sekcja: counterSection,
name: $scope.lang.formIn[counterSection].name,
data: []
};
console.log(name);
if (!$scope.formOut[counterSection]) {
$scope.formOut.push(newData);
}
$scope.formOut[counterSection].data.push($scope.Question);
$scope.formOut[counterSection].data[counterAsk].value = data;
counterAsk++;
// zmieniamy sekcje
if (counterAsk == $scope.lang.formIn[counterSection].data.length) {
counterAsk = 0;
counterSection++;
}
if (counterSection == $scope.lang.formIn.length) {
$scope.Question = '';
/* zrobic ukrycie pola z formularza */
} else {
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
}
/* konwertowanie do jsona */
//var Json = angular.toJson($scope.formOut);
//console.log(Json);
};
$scope.submit = function() {
alert('form sent'); /* wysĹanie formularza */
};
$scope.getClass = function(b) {
return b.toString();
};
}
]);
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
app.config(['$tooltipProvider',
function($tooltipProvider) {
$tooltipProvider.setTriggers({
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur',
'never': 'mouseleave',
'show': 'hide'
});
}
]);
var ValidSubmit = ['$parse',
function($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if (form.$valid) {
fn(scope, {
$event: event
});
}
});
});
scope.$watch(function() {
return form.$valid
}, function(isValid) {
if (form.$submitted == false)
return;
if (isValid) {
element.removeClass('has-error').addClass('has-success');
} else {
element.removeClass('has-success');
element.addClass('has-error');
}
});
}
};
}
};
}
];
app.directive('validSubmit', ValidSubmit);
I cant figure out what is the problem.
Thanks in advance.
Try changing your ngClick button handler to an ngSubmit form handler and wiring that up. You didn't say what browser you're using, but most of them auto-submit forms on an ENTER keypress unless you trap it (which you aren't). Clicking a button won't do this.

Resources