What is the angular way for cloning buttons? - html

I have a follow button for a particular user that should change its text to followed after it's clicked and vice versa. This follow button can show up in different modules on the page. When it's clicked, the follow button for this particular users should update in all of these modules. However, the buttons are in different scopes. What is the angular way of making sure the cloned buttons are in the same state?
My current solution is to use an universal jQuery selector to update all the buttons on click.

You should store the state in a service.
example:
app.factory('SharedService', function() {
this.buttonState = null;
this.setButtonState= function(value) {
this.buttonState = value;
}
this.getButtonState= function() {
return this.buttonState ;
}
return this;
});
Read: AngularJS Docs on services
or check this Egghead.io video

You can use $rootScope.$broadcast to do this. when any of button gets clicked you fire an event using $rootScope.$broadcast and then listen to it using $scope.$on and toggle the status of buttons. and you can also update state inside the service too, so you can fetch current value later if needed.
See the below example:
var app = angular.module('app', []);
app.controller('ctrl1', function($scope) {
$scope.label1 = "First Button";
});
app.controller('ctrl2', function($scope) {
$scope.label2 = "Second Button";
});
app.controller('ctrl3', function($scope) {
$scope.label3 = "Third Button";
});
// updating state in service too.
app.service('fButtons', function($rootScope) {
var buttonState = false;
this.getCurrentState = function() {
return buttonState;
};
this.updateCurrentState = function() {
buttonState = !buttonState;
};
});
app.directive('followButton', function($rootScope, $timeout, fButtons) {
return {
restrict: 'E',
scope: {
label: '='
},
template: '<button ng-click="buttonClick()" ng-class="{red: active}">{{label}}</button>',
controller: function($scope) {
$scope.$on('button.toggled', function() {
$scope.active = !$scope.active;
});
$scope.buttonClick = function() {
fButtons.updateCurrentState();
$rootScope.$broadcast('button.toggled');
console.log(fButtons.getCurrentState());
}
}
};
});
.red {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="ctrl1">
<follow-button label="label1"></follow-button>
</div>
<hr/>
<div ng-controller="ctrl2">
<follow-button label="label2"></follow-button>
</div>
<hr/>
<div ng-controller="ctrl3">
<follow-button label="label3"></follow-button>
</div>
</div>
see console for service state.
$broadcast docs

Related

Disable Pagination based on button

I have tried a few things currently from what I could search online however I, unfortunately, haven't found anything.
enter image description here
I would like to disable the pagination when I click on the replace button. Since it's loading with a spinner and there is a wait I thought it would make sense to disable it but not remove it. I know how to remove, both on the css side and angularjs. However, in all honesty, I am unsure how to disable this particular feature compared to other works that I have done.
HTML:
<button class="btn btn-blue" ng-click="handleLoadAndDeactivate()"
ng-show="'Load' == importAction && 0 == errors"
title="Load">
Replace
</button>
AngularJS (Button):
$scope.handleLoadAndDeactivate = function () {
$scope.onCompleteData.targetBody.withDeactivation = true;
onComplete($scope.onCompleteData, $scope.handleLoadAndDeactivateCompleted);
};
AngularJS (Table):
$scope.operationsPreloadCompletedTableOptions = new NgTableParams({}, {
dataset: importLog
});
html
Here's how you could achive this:
(function () {
"use strict";
const app = angular.module("app", []);
app.controller("app.AppCtrl", ($scope, $timeout) => {
$scope.disablePagination = false;
$scope.handleReplace = () => {
$scope.disablePagination = true;
//Your replace logic goes here
$timeout(() => {
$scope.disablePagination = false;
}, 2000);
};
}
);
})();
body {
margin: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="app.AppCtrl">
<button ng-disabled="disablePagination"><</button>
<button ng-disabled="disablePagination">1</button>
<button ng-disabled="disablePagination">2</button>
<button ng-disabled="disablePagination">></button>
<button ng-click="handleReplace();">Replace</button>
</div>

Is there a way to add a behavior(s) dynamically?

I want to add a behavior after a component/behavior already loaded or a certain function that will add a behevaior to its components.
Something like this:
<script>
// samplebehavior.html file
// this is the behavior file
samplebehavior = {
testAlert: function(){
alert('test');
}
};
</script>
// my-component.html
<script>
Polymer({
is: "my-component",
test: function() {
url = "samplebehavior.html";
var importHTML = new Promise(function(resolve, reject) {
Polymer.Base.importHref(url, function(e) {
resolve(e.target);
}, reject);
});
importHTML.then(function(element) {
// add a behavior here
// I know this script does not work
this.push('behaviors', samplebehavior);
});
}
});
</script>
So that I can access the testAlert() function.
How to I add a behavior dynamically?
To the best of knowledge it's not possible.
Behaviors are mixed in with the element definition when the prototype is built.
What you could do is generate the behaviors array dynamically
var behavior = {
properties: {
smth: {
value: 'initial value'
}
}
}
Polymer({
is: 'my-elem',
behaviors: getBehaviors()
});
function getBehaviors() {
return [ behavior ];
}
Remember though that getBehaviors will only ever be called once. After that you won't be able to change behaviors of your elements.
It's ugly but you can copy all members of your behavior in your object
<script>
// samplebehavior.html file
// this is the behavior file
samplebehavior = {
testAlert: function(){
alert('test');
}
};
</script>
// my-component.html
<script>
Polymer({
is: "my-component",
test: function() {
url = "samplebehavior.html";
var importHTML = new Promise(function(resolve, reject) {
Polymer.Base.importHref(url, function(e) {
resolve(e.target);
}, reject);
});
importHTML.then(function(element) {
for (let member in samplebehavior) {
this[member] = samplebehavior[member];
}
});
}
});
</script>
Or maybe you can call the internal method _prepBehavior() https://github.com/Polymer/polymer/blob/ff6e884ef4f309d41491333860a8bc9c2f178696/src/micro/behaviors.html#L111
But i don't know if that can do side effects
<script>
// samplebehavior.html file
// this is the behavior file
samplebehavior = {
testAlert: function(){
alert('test');
}
};
</script>
// my-component.html
<script>
Polymer({
is: "my-component",
test: function() {
url = "samplebehavior.html";
var importHTML = new Promise(function(resolve, reject) {
Polymer.Base.importHref(url, function(e) {
resolve(e.target);
}, reject);
});
importHTML.then(function(element) {
this.push('behaviors', samplebehavior);
this._prepBehaviors();
});
}
});
</script>
With introduction to new value for lazyRegister setting this has become partially possible.
By partially i mean you can only do this if you can edit the code of the element in which you want to add the behavior.
Three changes you'll require to add behavior dynamically are
Set lazyRegister setting to max
window.Polymer = {
lazyRegister:"max"
};
Just like #tomasz suggested, in the element you want to add behavior dynamically add behaviors using a function. This is so, because we won't be able to access the element from where we'll try to add new behavior dynamically(atleast i was not able to).
Polymer({
.
.
behaviors: getBehavior(),
.
.
});
function getBehavior(){
var myArr = [myBehavior];
document.addEventListener('add-behavior',function(e){
debugger;
myArr.push(e.detail);
});
return myArr;
}
From the element where you want to dynamically add the behavior use beforeRegister callback to dispatch an event adding the new behavior object
beforeRegister: function(){
var event = new CustomEvent('add-behavior',{
detail:{
func: function(){console.log(this.myProp,"!")}
}
});
document.dispatchEvent(event);
}
Here's a plunkr for working example.

Google Maps not working on tab Ionic

I create tab on Ionic project. When i would access to Google map from another url Tab, it's not working but when i access it directly it works.
First the Ionic part:
The tab showing the map is:
Ionic calls refreshMap() when the user selects the tab.
refreshMap() is:
.controller('MainCtrl', function($scope) {
$scope.refreshMap = function() {
setTimeout(function () {
$scope.refreshMap_();
}, 1); //Need to execute it this way because the DOM may not be ready yet
};
$scope.refreshMap_ = function() {
var div = document.getElementById("map_canvas");
reattachMap(map,div);
};
})
I've implemented reattachMap() looking at the Map.init() method:
function reattachMap(map,div) {
if (!isDom(div)) {
console.log("div is not dom");
return map;
} else {
map.set("div", div);
while(div.parentNode) {
div.style.backgroundColor = 'rgba(0,0,0,0)';
div = div.parentNode;
}
return map;
}
}
function isDom(element) {
return !!element &&
typeof element === "object" &&
"getBoundingClientRect" in element;
}
And that's about it, now when the user switches back to the map tab, it will be there.
Please refer this.
(https://github.com/mapsplugin/cordova-plugin-googlemaps/issues/256/#issuecomment-59784091)

how to disable ng-click event in confirmation Popup Button

How to disable ng-click event in confirmation Popup Button
1[Screen-Shot]
You can create a direcftive like this one :
app.directive('ngConfirmClick', [
function(){
return {
link: function (scope, element, attr) {
var msg = attr.ngConfirmClick || "Are you sure?";
var clickAction = attr.confirmedClick;
element.bind('click',function (event) {
if ( window.confirm(msg) ) {
scope.$apply(clickAction);
}
});
}
};
}]);
You use it this way :
<button confirmed-click="YourFunction()" ng-confirm-click="Are you really sure you want to do this ?">Action</button>

Angular service not storing data between two controllers

I am trying to use a service to set title in controller1 and then access title in controller2.
sharedProperties.setTitle(title) works in controller1, but when I try to get the title in controller2, it gets "title" (the initial value) instead of the new value.
I've also tried storing title in an object but it didn't work.
app.service('sharedProperties', function () {
var title = "title"
return {
getTitle: function () {
return title;
},
setTitle: function (val) {
title = val;
}
}
});
app.controller('controller1', ['$scope', 'sharedProperties', function ($scope, sharedProperties) {
$('body').on("click", "button[name=btnListItem]", function () {
// gets the title
var title = $(this).text();
// sets the title for storage in a service
sharedProperties.setTitle(title);
});
}]);
app.controller('controller2', ['$scope', 'sharedProperties', function ($scope, sharedProperties) {
$scope.sharedTitle = function() {
return sharedProperties.getTitle();
};
}]);
And in my view, I have {{ sharedTitle() }} which should, as I understand it, update the title text with the new title.
Also, in case this is relevant: the two controllers are linked to two different html pages.
What am I doing wrong?
EDIT
Updated button listener:
$('body').on("click", "button[name=btnListItem]", function () {
// gets the text of the button (title)
var title = $(this).text();
sharedTitle(title);
alert(sharedProperties.getTitle());
document.location.href = '/nextscreen.html';
});
$scope.sharedTitle = function (title) {
sharedProperties.setTitle(title);
};
It seems to be correct in your sample code. I setup jsfiddle and it seems work correctly. Finding out a difference between my jsfiddle and your actual code would help you to find the problem you should solve.
Javascript:
angular.module('testapp', [])
.service('sharedProperties', function(){
var title = 'title';
return {
getTitle: function(){
return title;
},
setTitle: function(val){
title = val;
}
};
})
.controller('controller1', function($scope, sharedProperties){
$scope.change_title = function(newvalue){
sharedProperties.setTitle(newvalue);
};
})
.controller('controller2', function($scope, sharedProperties){
$scope.sharedTitle = function(){
return sharedProperties.getTitle();
};
})
Html:
<div ng-app="testapp">
<div ng-controller="controller1">
<input ng-model="newvalue">
<button ng-click="change_title(newvalue)">Change Title</button>
</div>
<div ng-controller="controller2">
<span>{{sharedTitle()}}</span>
</div>
</div>
My jsfiddle is here.
You have to print console.log(sharedProperties.getTitle()); Dont need return from controller.
So your code of controller2 is $scope.sharedTitle = sharedProperties.getTitle();
You need to use the $apply so that angular can process changes made outside of the angular context (in this case changes made by jQuery).
$('body').on("click", "button[name=btnListItem]", function () {
// gets the title
var title = $(this).text();
// sets the title for storage in a service
$scope.$apply(function() {
sharedProperties.setTitle(title);
});
});
See plunker
That said, this is BAD PRACTICE because you're going against what angular is meant for. Check “Thinking in AngularJS” if I have a jQuery background?. There are cases when you need to use $apply like when integrating third party plugins but this is not one of those cases.