Import same information to modal - javascript

It's an ad (discount codes for e-shops) app I'm trying to make.
Ads are listed in to Array , each ad having 4 things (name, image link , discount (%) , discount code)
This is how I list the ads (ng-repeat is used) :
<div class="list">
<div class="item item-thumbnail-left" href="#" ng-repeat="item in dovanosListArray" >
<img ng-src={{item.image}}>
<h2>{{item.name}}</h2>
<button menu-toggle="right"class="button-icon icon ion-ios7-arrow-forward" ng-click="modal.show()"></button>
<p>Nuolaida : {{item.discount}} %</p>
</div>
</div>
So when you click the one you want, modal opens. In the modal , I need to show the same {{item.name}} again and give it's {{item.discountcode}}. How am i supposed to do this ? I can't use ng-repeat because there are other items in the same array as well.

Sorry for my English, I think that you need is something like this:
var modalInstance = $modal.open({
templateUrl: 'Modal.html',
controller: 'ModalCtrl',
resolve: {
item: function () {
return item;
}
}
And in you controller:
angular.controller('ModalCtrl', ['$scope','item',
function($scope, item , ) {
$scope.item=tem;
..........................
}])
So in your controller you already hace the value of item;

Pass the item as an object parameter in your modal.show() function.

Related

Display div with a hint only if one specific option is chosen/active. AngularJS

I am working on the AngularJS project and I have a page that injects a component with 3 different buttons. I need to display a hint to this button only when one of them is clicked/active/chosen (no need to display anything for another 2). I bet this should be solved with binding but I am not sure how to do it properly.
Can you advise, please?
Here is my code.
Main page HTML:
<ch-form-group
title="Which notification should be sent?"
header="Define the notification that you want to send out to the qualifying customers.">
<ch-toggle-blocks
toggle-blocks="$ctrl.event_action_params"
on-block-clicked="$ctrl.toggleEventAction(toggleBlock.key)">
</ch-toggle-blocks>
// I want to display block here. So when inside the ch-toggle-blocks user // chose only specific button
<notification-form
channel-type="$ctrl.getChannelType()"
channel="$ctrl.getChannel()">
</notification-form>
</ch-form-group>
ch-toggle-block HTML
<div class="ch-toggle-blocks">
<div
data-hook="toggle-block-selector"
class="toggle-block"
ng-click="$ctrl.clickBlock(toggleBlock)"
ng-class="{'current-toggle-block': toggleBlock.is_current}"
ng-repeat="toggleBlock in $ctrl.toggleBlocks">
<span
data-hook="current-toggle-block-label"
class="label label-cityhive"
ng-if="toggleBlock.is_current">
Current
</span>
<div class="toggle-block-icon">
<i class="{{toggleBlock.icon}}"></i>
</div>
<div class="toggle-block-name">
<span>{{toggleBlock.friendly_name}}</span>
</div>
</div>
</div>
chToggleBlocksComponent.js
'use strict';
angular.module('MyModule')
.component('chToggleBlocks', {
bindings: {
toggleBlocks: '<',
onBlockClicked: '&'
},
templateUrl: 'ch_toggle_blocks/chToggleBlocks.html',
controller: function() {
var ctrl = this;
ctrl.clickBlock = function(toggleBlock) {
this.onBlockClicked({toggleBlock: toggleBlock})
}
}
});
So, basically, when {{toggleBlock.friendly_name}} with the text "SMS" is active, I need to display another div on the main page.

Append / add, text and function to a div's content

I'm currently working on a AngularJS based application. I'm using the 'pascalprecht.translate' library to create a multi-language application. For more information on that please see this link. While creating my application i've created a dynamic switch of page titles. this switch reads the route name from the $routeProvider and adds a corresponding title to the <header>. See the example below:
// Pages configuration
myApp.run(['$rootScope', '$route', function($rootScope, $route) {
$rootScope.$on('$routeChangeSuccess', function() {
document.title = $route.current.title;
var title = document.getElementsByTagName("title")[0].innerHTML;
var leftSvg = document.getElementById('leftsvg');
var rightSvg = document.getElementById('rightsvg');
// start responsive elements
$("footer").removeClass("hidden-xl-down");
$("#header").removeClass("hidden-xl-down");
$("#leftheaderblock").removeAttr('class');
$("#rightheaderblock").removeAttr('class');
$(".activefooter").removeAttr('class');
$("#homepageback").removeClass("hidden-xl-down");
$("#rightsvg").addClass("hidden-xl-down");
$("#leftsvg").addClass("hidden-xl-down");
$("body").removeAttr('class');
$("body").addClass(title);
if (title === 'login') {
$("footer").addClass("hidden-xl-down");
$("#header").addClass("hidden-xl-down")
}
else if (title === 'productpage') {
$("#homepageback").addClass("hidden-xl-down");
$("#homesvg").addClass("activefooter");
$("#leftheaderblock").addClass("col-55");
$("#rightheaderblock").addClass("col-45");
$('#leftheadertext').text('Alle producten');
$('#rightheadertext').text('Bestelling');
$("#rightsvg").removeClass("hidden-xl-down");
$("#leftsvg").removeClass("hidden-xl-down")
}
});
}]);
The html
The <html> is some simple div's in an index.html file. Below you'll see the example of the rightheaderblock.
<div id="rightheaderblock">
<div class="bc-f3f3f3 justify-content-center toptext d-flex align-items-center headerblock">
<span id="rightheadertext"></span>
</div>
</div>
The question
Using 'pascalprecht.translate' gives access to the possibility of creating a multiple language application with your own language library's in JSON format. See the example below:
var myApp = angular.module('myApp',['ngRoute','pascalprecht.translate','ngSanitize']);
var mypagetitle = document.getElementsByTagName("title")[0];
myApp.config(function ($routeProvider, $locationProvider, $translateProvider) {
$locationProvider.hashPrefix('');
$routeProvider
.when('/', {
templateUrl: 'views/login_view.html',
title: 'login'
})
.when('/productpage', {
templateUrl: 'views/productpage_view.html',
title: 'productpage'
})
.when('/payorder', {
templateUrl: 'views/payorder_view.html',
title: 'payorder'
});
$translateProvider
.translations('en', {
'Opslaan': 'Save',
'Alle producten': 'All products',
'Bestelling': 'Order',
})
.translations('nl', {
'Opslaan': 'Opslaan',
'Alle producten': 'Alle producten',
'Bestelling': 'Bestelling',
});
$translateProvider.useSanitizeValueStrategy('sanitize');
$translateProvider.preferredLanguage('nl'); // standaard taal bij openen
// configures staticFilesLoader
// configures staticFilesLoader
});
myApp.controller('mainCtrl', function($http, $scope) {
$scope.text = "hi";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="main" ng-controller="mainCtrl">
<div id="rightheaderblock">
<div class="bc-f3f3f3 justify-content-center toptext d-flex align-items-center headerblock">
<span id="rightheadertext">
{{text}}
</span>
</div>
</div>
<div class="bodyTests">
<p> {{ "Bestelling" | translate }}
</div>
Above you're able to look at a simple example of how the 'tranlate' function works. by adding | translate to a string and defining that string to a .translations() section i'm able to create the translations.
Looking back at the // Pages configuration above you're able to see that i'm using if/else statements to check for the page title and add .text() and classes to a div by current page title.
The issue i'm having is passing the | translate section of e.g. {{"bestelling" | translate}} from the if/else statement to the view. So passing the following line:
$('#rightheadertext').text('Bestelling');
To the page isn't a problem. But adding
$('#rightheadertext').text('{{ Bestelling | translate }}');
gives me the full string in the view:
{{ Bestelling | translate }}
i've tried multiple different functions like .val() and append(). But neither seems to work. The result i would like is to add the following structure to the view:
{{ "string" | translate // call }}
If you have any questions or remarks on my question please let them know in the comments below.
As always, thanks in advance!
How about this...
<p> {{ $root.text1 | translate }}</p>
Then in your code, in the if/else...
if (...) {
$rootScope.text1 = 'Bestelling';
} else {
$rootScope.text1 = 'Opslaan';
}

Getting ID of the first item only on using ng-repeat

So here's my workflow-
I've got an HTML file in which a div tag is created on which I've placed ng-repeat which iterates and gives me a list of items. On this div tag, I've placed an ng-click function. On clicking and item in the div tag, a modal-popup is opened.
What I need is to pass the id of the item from ng-repeat and show the data of this id in the modal-popup.
Now I've written the code upto here and all things are working fine, but the issue that I'm facing is if I click on any of the items from ng-repeat the first item is only returned, and hence data for the id of the first item is only being displayed in the modal-popup.
How could I get the id of the particular item clicked (and not the first item) and pass it to the controller?
Here's my working code -
main HTML:
<div id="main">
<div ng-repeat="data in JsonData" ng-click="openModal()">
<div id="widget">
<div id="{{$index}}">
<div>
<h2 class="font-bold no-margins" id="{{data.itemName}}">
{{data.itemName}}
</h2>
</div>
<div>
// other code
</div>
</div>
</div>
</div>
</div>
main controller.js:
$scope.openModal = function () {
$rootScope.elementid = document.getElementById('main').getElementsByTagName('div')[2];
$rootScope.variableId = $scope.elementid.id; // This gives the value in {{$index}}
$rootScope.elementname = document.getElementById('main').getElementsByTagName('h2')[0];
$rootScope.variablename = $scope.elementname.id; // This gives the value in {{data.itemName}}
$uibModal.open({
templateUrl: 'url/to/modal/popup.html',
controller: 'PopUpController',
scope : $scope,
windowClass: "animated fadeIn",
backdrop:'static'
});
};
On doing inspect element, I found that the elements are getting their correct id.
This is for the {{itenName}} code: (names are coming correct)
h2#CorrectName.ng-binding
and this is for the {{$index}} code: (here, id is incrementing for the items of ng-repeat)
div#0.ng-binding
So where am I wrong here? Is it due to any asynchronous call? Or is it due to ng-binding (i.e id of the item is returned before the ng-binding function completes)?
I'm really stuck here for a couple of days now. Any help would be much appreciated. Thanks.
You should not get the HTML data, instead you should pass the values to your function
ng-click="openModal(data)"
and from that on you can get the data in your funtion
$scope.openModal = function (data) {
and now you can do with that data whatever you want
console.log(data.itemName)
angular.module('test', []).controller('test', function($scope) {
// Test data
$scope.JsonData = [{itemName: "Test"}, {itemName: "OtherTest"}];
$scope.openModal = function(data) {
// handling data
console.log(data);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="test">
<div ng-repeat="data in JsonData" ng-click="openModal(data)">
<div id="widget">
<div id="{{$index}}">
<div>
<h2 class="font-bold no-margins" id="{{data.itemName}}">
{{data.itemName}}
</h2>
</div>
</div>
</div>
</div>
</div>
you can pass your $index to ng-click="openModal()" , so it will be ng-click="openModal($index)" .
controller
$scope.openModal = function (id) {
console.log(id); // log the clicked id
}
you can pass selected JsonData object as parametr of openModal function
<div ng-repeat="data in JsonData" ng-click="openModal(data)">
also you can pass selected obj to modal controller
$scope.openModal = function (selectedObj) {
$uibModal.open({
templateUrl: 'url/to/modal/popup.html',
controller: 'PopUpController',
scope : $scope,
windowClass: "animated fadeIn",
backdrop:'static',
resolve : {
selected: function () {
return selectedObj;
}
}
});
};
and get selected obj in PopUpController
app.contoller('PopUpController',['selected', function(selected){
console.log(selected)
}])

Angular JS ng-repeat element does not update

I have to display a list of products and be able to click on them to get more informations about them.
My list of products is stored in a service named: "productsServices"
I got an html page who display all my products and an other who display details for 1 product. Each html page have their own controller.
When I update a product in my detail page, the changement is done in my productsServices but are not validated in my global product view.
(function ()
{
angular.module('app').service('productsServices', ['$http', '$q', ProductsServices])
that = this
that.products = /*arrayOfData*/;
that.getProducts = function () {
return that.products;
}
})();
(function ()
{
angular.module('app').controller('ProductsController', ['$http', '$q', 'productsServices', ProductsController])
that = this
that.products = productsServices.getProducts;
that.showDetail = function (item) {
$state.go('menu.product', { myParam: item });
}
})();
<!--Global HTML page-->
<ion-content id="content" class="has-header has-subheader" delegate-handle="myScroll">
<ion-list>
<ion-item ng-repeat="product in that.products() track by product.ProductId" href="#" ng-click="that.showDetail({{product}})">
<div class="innerProd">
<img id="productPicture" name="productPicture" ng-src='data:image/png;base64,{{product.ThumbnailPhoto}}'></div>
<div class= "innerProd">
<p>{{product.Name}}</p>
<p>{{product.Price}}$</p>
<ion-option-button class="button button-assertive"
ng-click="doDelete({{product}})">
Supprimer
</ion-option-button>
</div>
</ion-item>
</ion-list>
<ion-infinite-scroll ng-if="moreDataCanBeLoaded()" icon="ion-loading-c" on-infinite="loadMoreData()" distance="100%">
</ion-infinite-scroll>
</ion-content>
So when I check the product sended in the "that.showDetail" method, it's the old product who is sended even if the product have been updated in the services.
I'm not english so sorry for language mistakes in my sentence ^^'
Thank in advance for your help ^^'
Ok I've find the ansewer to my question, I've replace the parameter that I'm sending to my "that.showDetail" function. I'm no more sending the object directly, but the index of my item.
<ion-item ng-repeat="product in that.products() track by product.ProductId" href="#" ng-click="that.showDetail({{$index}})">
I guess that angular doesn't update injected in a ng-click call ^^'
Thank you for your time guys

What is setSize in ng-click?

I'm trying to study API (I also looked up the meaning of that also and isn't it a small area on a page that are programmed to function in what it's coded for (for example, a box in which you set the alarm and have it ring at certain time, correct?)) at https://www.barkbox.com/subscribe/size.
I know that it's in Angular JS and I even study Angular UI router. I know that you can program the links to go to another page without reloading the page and this is similar to what I was looking for. For example, ui-sref="home" will call the code from home.html. Also, in ngRoute method, you use a href="#about" to call the code from about.html. But I don't see both in that Barkbox app at this link I provided.
The only clue to which I think would cause this barkbox app to work is ng-click="setSize('squee')". I think what it did was to set the size of the box and link the whole box to another page and somehow use this code or something similar:
// app.js
var routerApp = angular.module('dogApp', ['ui.router']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
// HOME STATES AND NESTED VIEWS ========================================
.state('home', {
url: '/home',
templateUrl: 'partial-home.html'
})
// ABOUT PAGE AND MULTIPLE NAMED VIEWS =================================
.state('about', {
// we'll get to this in a bit
});
});
I really learned much from studying https://scotch.io/tutorials/angular-routing-using-ui-router and https://scotch.io/tutorials/single-page-apps-with-angularjs-routing-and-templating. But I have yet to study more at https://github.com/angular-ui/ui-router.
Still, I'm trying to understand setSize function as well ng-click as in how they can link to another page. I tried to look it up but couldn't find info on that and its connection to ng-click or something like that.... Any help or suggestions are appreciated.
---------------Update----------------------
Okay, I made the code. You can see it at http://hamzakhan.name/dev/eric/options/dogsubscription.html#/dogs
html code is
<div class="optionwrapper size">
<div class="option" ng-click="setSize('one')">
<div class="numberimage1"></div>
<div class="numbercontent">
<div class="numbertitle">One</div>
</div>
<div class="icon-chevron-right"><i class="fa fa-angle-right fa-3x"></i></div>
</div>
</div>
<div class="optionwrapper size">
<div class="option" ng-click="setSize('two')">
<div class="numberimage2"></div>
<div class="numbercontent">
<div class="numbertitle">Two</div>
</div>
<div class="icon-chevron-right"><i class="fa fa-angle-right fa-3x"></i></div>
</div>
</div>
and javascript code is
angular.module('dogApp', ['ui.router'])
// configuring our routes
// =============================================================================
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show our basic form (/form)
.state('dogs', {
url: '/dogs',
templateUrl: 'dogs.html',
controller: 'dogController'
})
// nested states
// each of these sections will have their own view
// catch all route
// send users to the form page
$urlRouterProvider.otherwise('/dogs');
})
// our controller for the form
// =============================================================================
.controller('dogController', function($scope) {
// we will store all of our form data in this object
$scope.dogData = {};
// url will be nested (/dogs-oneage)
$scope.setSize = function(one) {
//url: '/oneage',
templateUrl: 'dogs-oneage.html'
}
// url will be nested (/dogs-twoage)
$scope.setSize = function(two) {
//url: '/twoage',
templateUrl: 'dogs-twoage.html'
}
// url will be nested (/dogs-threeage)
$scope.setSize = function(three) {
//url: '/threeage',
templateUrl: 'dogs-threeage.html'
}
// url will be nested (/dogs-fourage)
$scope.setSize = function(four) {
//url: '/fourage',
templateUrl: 'dogs-fourage.html'
}
// url will be nested (/dogs-fiveage)
$scope.setSize = function(five) {
//url: '/fiveage',
templateUrl: 'dogs-fiveage.html'
}
// function to process the form
$scope.processForm = function() {
alert('Congratulations! You have finished the first part! Please complete the second part to finish registering.');
};
});
but no matter what, I couldn't get the boxes to link to another page.... :(
this is the name of the function in your controller.
Basicly ng-click is: 'when you click here, this function will be called'.
So when you click on the <div> or <a> the function setSize() will becalled. 'squee' is the parameter passed to the function.
What the function does is written in the controller that is instantiated for the specific page/part of the page. You should look for a piece of code similar to: $scope.setSize = function(param) {}
Answer to your updated code:
You can add $location in your controller. An example would look like this:
routerApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/one', {
templateUrl: '<*the complete link to your html file*>'
})
.when('/two', {
templateUrl: '<*the complete link to your html file*>'
})
.otherwise({
redirectTo: '/home',
templateUrl: '<*the complete link to your html file*>'
});
}])
.controller('dogController',['$scope', '$location', function($scope, $location) {
$scope.goTo = function(url) {
$location.path(url);
}
}
And then your HTML:
<div class="optionwrapper size">
<div class="option" ng-click="goTo('/one')">
<div class="numberimage1"></div>
<div class="numbercontent">
<div class="numbertitle">One</div>
</div>
<div class="icon-chevron-right"><i class="fa fa-angle-right fa-3x"></i></div>
</div>
</div>
<div class="optionwrapper size">
<div class="option" ng-click="goTo('/two')">
<div class="numberimage2"></div>
<div class="numbercontent">
<div class="numbertitle">Two</div>
</div>
<div class="icon-chevron-right"><i class="fa fa-angle-right fa-3x"></i></div>
</div>
</div>
What happens here: you tell your app that when the url matches ".com/one" it will open template one. Your div now has ng-click=goTo('/one'), and then with $location.path it will direct to the url ".com/one".
The setSize() method you wanted to use from the tutorial is a name you can change to whatever you want. In the tutorial it was probably called setSize because it adjusted the size of something. Here I renamed it to goTo() because you want to go to a certain url.
With this code I provided you should be able to manage and get it working now :-) Good luck!

Categories

Resources