What is setSize in ng-click? - javascript

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!

Related

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

Can Siblings Controllers communicate with each other without the help of the Parent - AngularJS

I'm working on a small app in AngularJS. My project contain a Body.html file that contain 3 views: SideMenu, Header and Content, each with each own Controller and a MainController as there parent - the controller of the Body.html.
Can the header's controller change a property in the side-menu - the open/close status of the side-menu.
And Can the side-menu controller change a property in the header - the header's text.
I can use the main controller, since both of the header's controller and the side-menu controller can reference the main controller. But the data won't be consist. Updating the data from the 1st controller wan't effect the data in the 2nd controller (without the use of $watch).
Can both the side-menu's controller and the header's controller (sibling controllers) communicate with each other? without the help of there parent?
Body.html
<div>
<!-- Header placeholder -->
<div ui-view="header"></div>
<!-- SideMenu placeholder -->
<div ui-view="sideMenu"></div>
<!-- Content placeholder -->
<div ui-view></div>
</div>
Header.html
<div>
{{ headerCtrl.text }}
</div>
<div ng-click="headerCtrl.openSideMenu()">
--Open--
</div>
HeaderController.js
// sideMenuCtrl = ???
headerCtrl.text = "Title";
headerCtrl.openSideMenu = function()
{
sideMenuCtrl.isSideMenuOpen = true;
};
SideMenu.html
<div ng-class={ 'side-menu-open': sideMenuCtrl.isSideMenuOpen }>
<div ng-repeat="menuItem in sideMenuCtrl.sideMenuItems"
ng-click="sideMenuCtrl.selectMenuItem(menuItem)">
{{ menuItem.text }}
</div>
</div>
SideMenuController.js
// headerCtrl = ???
sideMenuCtrl.selectMenuItem = function(menuItem)
{
headerCtrl.text = menuItem.text;
}
As stated in my comment, you can use an AngularJS service to share some data between your controllers.
app.service('AppContextService', function(){
this.context = {
isSideMenuOpen: false
};
});
app.controller('SideMenuCtrl', ['$scope', 'AppContextService', function($scope, AppContextService) {
// exposing the application context object to the controller.
$scope.appContext = AppContextService.context;
}]);
app.controller('HeaderCtrl', ['$scope', 'AppContextService', function($scope, AppContextService) {
$scope.appContext = AppContextService.context;
$scope.openSideMenu = function()
{
$scope.appContext.isSideMenuOpen = true;
};
}]);
Then adapt the HTML to use your shared appContext object.
<div ng-class={ 'side-menu-open': appContext.isSideMenuOpen }>
[...]
</div>
Here is a working fiddle that illustrates the issue: fiddle
This answer covers the use of a service to fit your needs but I am sure that there are other (and perhaps better) ways to tackle the problem which might involve other Angular feature, or even some overall application refactoring.
To dig a little deeper, this SO topic might be a good start: difference between service, factory and providers

Issues with $location in Angularjs

I have a single page app '(Backend in Python/Django)' where my functions return json response and that json response handled by angular js in front end . I am using angular ajax call to hit the function. Now we all know that on ajax call url in address bar do not get changed. But in angular js we can set url using $location.path(). So it keeps the history of url I have visited and on browser back button it changes the url in address bar to previous one . But it do not change the content of the page.
My angular ajax call :
app.controller('myController',
function($scope,$http, $location, $route, $timeout){
$scope.formData={}
$scope.getAllBrainframes=function(id){
if(id){
$scope.url = '/get-brainframe/'+id+'/';
}else{
$scope.url = '/get-brainframe/';
}
$http.post($scope.url)
.success(function(data,status){
.success(function(data,status){
$scope.title = data[0].title
$scope.brainframes = data;
$location.path($scope.url);
$scope.parent= data[0].id;
})
.error(function(data,status){
});
}
});
As I am setting $location.path() on ajax success , so it appends the current visited url in address bar and keeps history of every url i have visited. But when I click on browser back button it changes the url in address bar to previous one but not the content.
Now is there any function that i can trigger when I click on browser back button or how I can change the content of page ?
EDIT :
above ajax success function edited .
My html :
<div class="content">
<span ng-repeat="brainframe in brainframes">
<p ng-if = "brainframe.brainframes.length > 0 ">
<ul class="list-group col-md-5">
<div data-ng-repeat="brain in brainframe.brainframes" class="child-brainframes">
<a class="my-title" ng-click="getAllBrainframes(brain.brainframe_child.pk)">
<li class="list-group-item"><span class="badge">{$ brain.count_children $}</span>{$ brain.brainframe_child.title $}</li>
</a>
</div>
</ul>
</p>
<p ng-if = "brainframe.brainframes.length < 1 ">
<span>No brainframes are available.</span>
</p>
</span>
</div>
You need to look at $routeParams and change the content in the template.
DEMO
.controller("MainCtrl",
function($scope,$http, $location, $route, $timeout, $routeParams){
$scope.formData={};
$scope.id = $routeParams.id;
$scope.getAllBrainframes=function(id){
if(id){
$scope.url = '/home/'+id+'/';
}else{
$scope.url = '/home';
}
console.log($scope.url);
$location.path($scope.url);
};
});
In your template:
Check for the $scope property and show/hide
<script type="text/ng-template" id="Home.html">
<p>This is one template</p>
<p ng-if="id">This is in next template</p>
<a ng-click="getAllBrainframes('1')">next template</a>
</script>
Check full code here
UPDATED:
If you want to persist the ajax call data between routes, you need to probably store it in a service and access it in your controller based on the $routeParams from the service.

Import same information to modal

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.

AngularJS Only Show View If Server Data Present

In my regular Javascript I append data to HTML ONLY if there's data from the server, otherwise I just show a simple div saying there's nothing. How can I implement this in AngularJS?
Example:
if (AJAXresult)
$element.append(JSONdata); //JSONdata will contain a list of customer data
else
$element.append('<div>No results</div>');
How can I achieve this in Angular?
The simplest way would be to control for the no data state in your returned view.
<div>
<div ng-if="!hasCustomers">
No Customers Available
</div>
<div ng-if="hasCustomers">
<!-- show some stuff -->
</div>
</div>
Then in your controller you can easily initialize this when you load your data:
angular.module('myApp').controller('MyController', function($scope, myDataService){
$scope.hasCustomers = false;
myDataService.getCustomers()
.then(function(value){
$scope.customers = value.data;
$scope.hasCustomers = customers && customers.length;
});
});
If you want to make sure the data is loaded before your view is ever instantiated, then you can also use the resolve property on your $route
$routeProvider.when('/someRoute/',{
templateUrl: '/sometemplate.html',
controller: 'MyController',
controllerAs: 'ctrl', // <-- Highly recommend you do this
resolve: {
customerData: function(myDataService){
return myDataService.getCustomers();
}
}
});
resolve is basically a hash of functions that return a promise, and can be dependency injected just like everything else. The controller and view will not be loaded until all the resolve promises have been fulfilled.
It will be available in your controller by the same property name you gave it:
angular.module('myApp')
.controller('MyController', function($scope, customerData){
$scope.customers = customerData;
$scope.hasCustomers = customerData && customerData.length;
});

Categories

Resources