How do I communicate between sibling controllers? - html

Here's my code:
<div ng-controller="mainCtrl">
<button ng-click="onclick()"></button>
<button ng-click="onclick()"></button>
<button ng-click="onclick()"></button>
{{display}}
</div>
<div ng-controller="SecondController">{{display}}</div>
<div ng-controller="lastController">{{display}}</div>
I have to get some message in each div when the user clicks on the button.
I've tried the below code:
app.controller('mainCtrl',function($scope,$rootScope){
$scope.OnClick = function (msg) {
$rootScope.$broadcast("firstEvent",{});
}
$scope.$on("firstEvent", function (msg ) {
$scope.display = "hello world";
});
});
app.controller('SecondController',function( $scope){
$scope.$on("firstEvent", function (msg) {
$scope.display = "hello how Are you";
});
});
app.controller('lastController',function($scope) {
$scope.$on("firstEvent", function (msg) {
$scope.display = "this is my Query";
});
});
When the user clicks on each button, it should get data in each div.
How come its only possible with $on, $event and $broadcast?

$broadcast() sends an even downwards from parent to child controllers. The $emit() method, on the other hand, does exactly opposite. It sends an event upwards from the current controller to all of its parent controllers.
This is a simple example of communicating between controllers
angular.module("app", [])
.controller("mainCtrl", [
"$scope", "$rootScope",
function($scope, $rootScope) {
$scope.go = function(msg) {
if (msg == 1) {
$scope.display = "hello firstEvent";
} else if (msg == 2) {
$rootScope.$broadcast("showSomething", {});
} else {
$rootScope.$broadcast("showGoodBye", {});
}
};
}
]).controller("SecondController", [
"$scope", "$rootScope",
function($scope, $rootScope) {
$scope.$on("showSomething", function(msg) {
$scope.display = "hello Something";
});
}
]).controller("ThirdController", [
"$scope", "$rootScope",
function($scope, $rootScope) {
$scope.$on("showGoodBye", function(msg) {
$scope.display = "hello GoodBye";
});
}
]);
<div ng-app="app">
<div ng-controller="mainCtrl">
mainCtrl : {{display}}
<br>
<button ng-click="go(1)"> Show Hello </button>
<button ng-click="go(2)"> Show Something </button>
<button ng-click="go(3)"> Show GoodBye </button>
</div>
<hr>
<div ng-controller="SecondController">
SecondController : {{display}}
<hr>
</div>
<div ng-controller="ThirdController">
SecondController : {{display}}
<hr>
</div>
</div>
A complete Tour

Here is the solution:
I prefer not to use rootScope, you can use intermaeidate service to share data between two controllers
Solution with services:
Here is how service looks:
app.service('StoreService',function(){
var data;
this.save=function(data){
this.data=data;
};
this.getData=function(){
return this.data;
};
});
Using a service without rootScope
Demo without rootScope
Solution with rootScope
var app = angular.module('myApp', []);
app.controller('mainCtrl',function($scope,$rootScope){
$scope.buttonclick = function (msg) {
var object = {
data: msg
}
$rootScope.$broadcast("firstEvent",object);
}
$rootScope.$on("firstEvent", function (event, msg) {
$scope.display = msg.data;
});
})
app.controller('SecondController',function( $scope, $rootScope){
$rootScope.$on("firstEvent", function (event, msg) {
$scope.display = msg.data;
});
})
app.controller('lastController',function( $scope, $rootScope){
$rootScope.$on("firstEvent", function (event, msg) {
$scope.display = msg.data;
});
})
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="mainCtrl">
<button ng-click="buttonclick('button1')">button1</button>
<button ng-click="buttonclick('button2')">button2</button>
<button ng-click="buttonclick('button3')">button3</button>
<br>
{{display}}
</div>
<div ng-controller="SecondController">{{display}}</div>
<div ng-controller="lastController">{{display}}</div>
</div>
</body>
</html>
Please run the above snippet
Here is a Working DEMO

Related

Trigger preview mode by passing data from one controller to another

I want to trigger a preview mode from one controller onto another using angular service but can't get the final step done. I am trying to get the url from the passed parameter into that ng-src in SideMenuCtrl. Not sure how to do it so that it would happen dynamically.
I have seen a few similar threads but not with a final end result like mine because I am trying to eventually display an image on the screen.
How would I link the passed parameter advert to vm.previewImage/.
var app = angular.module('app', [])
.service('appState', function() {
this.data = {
preview: {
enabled: false,
advert: ''
}
};
this.previewAdvert = function(advert) {
//flick the inPreview variable
this.data.preview = {
enabled: !this.data.preview.enabled,
advert: advert
}
}
})
.controller('SideMenuCtrl', function(appState) {
var vm = this;
vm.preview = appState.data.preview;
})
.controller('ContentCtrl', function(appState) {
var vm = this;
vm.advertUrl = 'http://1.bp.blogspot.com/-vXmHgrrk4ic/UpTbgBkp8eI/AAAAAAAAFjQ/ajBQ9WvwNUc/s1600/gloomy-stripes-dark-background-tile.jpg';
vm.previewAdvert = function() {
console.log('preview/stop preview');
appState.previewAdvert(vm.advertUrl);
}
});
<html ng-app="app">
<body>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<div ng-controller="SideMenuCtrl as vm">
<div class="ads" ng-if="vm.preview.enabled">
<img ng-src="{{vm.previewImage}}">
</div>
</div>
<div ng-controller="ContentCtrl as vm">
<label for="adInput">Advert URL</label>
<input type="url" id="adInput" ng-model="vm.advertUrl"></input>
<button ng-mouseenter="vm.previewAdvert()" ng-mouseleave="vm.previewAdvert()">Preview</button>
</div>
</body>
</html>
Your service is shared all right between your controllers. However I noticed that with AngularJs properties from the controller are not always updated when their value change.
When this happens, you can use a function that returns your value and use the function call instead your value in your views. This way, updates are detected.
(NOTE: I moved the "SideMenuCtrl" div under because with the image appearing, the button was not hovered anymore, causing "mouseleave" to be called and that produced a flickering)
var app = angular.module('app', [])
.service('appState', function() {
this.data = {
preview: {
enabled: false,
advert: ''
}
};
this.previewAdvert = function(advert) {
//flick the inPreview variable
this.data.preview = {
enabled: !this.data.preview.enabled,
advert: advert
}
}
})
.controller('SideMenuCtrl', function(appState) {
var vm = this;
vm.getPreviewImage = function(){
return appState.data.preview.advert;
};
vm.isPreviewEnabled = function(){
return appState.data.preview.enabled;
};
})
.controller('ContentCtrl', function(appState) {
var vm = this;
vm.advertUrl = 'http://1.bp.blogspot.com/-vXmHgrrk4ic/UpTbgBkp8eI/AAAAAAAAFjQ/ajBQ9WvwNUc/s1600/gloomy-stripes-dark-background-tile.jpg';
vm.previewAdvert = function() {
console.log('preview/stop preview');
appState.previewAdvert(vm.advertUrl);
}
});
<html ng-app="app">
<body>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<div ng-controller="ContentCtrl as vm">
<label for="adInput">Advert URL</label>
<input type="url" id="adInput" ng-model="vm.advertUrl"></input>
<button ng-mouseenter="vm.previewAdvert()" ng-mouseleave="vm.previewAdvert()">Preview</button>
</div>
<div ng-controller="SideMenuCtrl as vm">
<div class="ads" ng-if="vm.isPreviewEnabled()">
<img ng-src="{{vm.getPreviewImage()}}">
</div>
</div>
</body>
</html>

How to add two methods on a #click event using vue.js?

This is my code and i basically want to add CHANGEBUTTONS to the on click event that looks like #click.
<button #click="enviarform2" value="Delete from favorites" style="font-weight: 700;color:#428bca;margin-left:30px;height:30px;border-radius:4px" name="delete" v-else>Delete from favorites</button>
<script>
new Vue({
el:'#app',
data:{
show: true,
paletteid : <?=$palette_id;?>,
action: "add",
action2: "delete",
number: ""
},
methods: {
enviarform: function() {
axios.post('/validarfavorite.php', {
paletteid: this.paletteid,
action: this.action
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
this.number = "Yours plus ";
},
enviarform2: function() {
axios.post('/validarfavorite.php', {
paletteid: this.paletteid,
action2: this.action2
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
this.number = "Minus yours plus ";
},
changebuttons: function() {
this.show = !this.show;
}
}
});
</script>
I have tried with method 1 and method 2 and handler but it didnt work. Hope you know!
You can separate the calls using a ; (or the comma operator):
<button #click="#click="m1(); m2()">my button</button>
<button #click="#click="m1(), m2()">my button</button>
But if your code is used in more than one place, though, the best practice (the "cleanest approach") is to create a third method and use it instead:
<button #click="mOneAndTwo">my button</button>
Demo:
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
},
methods: {
m1: function() { this.message += "m1"; },
m2: function() { this.message += "m2"; },
mOneAndTwo: function() {
/* call two methods. */
this.m1();
this.m2();
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p>{{ message }}</p>
<button #click="m1(); m2()">call two methods using ;</button><br>
<button #click="m1(), m2()">call two methods using ,</button><br>
<button #click="mOneAndTwo">call two methods using a third method</button><br>
</div>
The easiest way to do it is:
<button v-on:click="method1(); method2();">Continue</button>
Cant you simply call the methods inside the functions?

How can I pass controller scope to a partial html file?

This is my main HTML file.
<div ng-controller="filterController">
<div class="quick-view" id="quickview" data-toggle="modal" data-target="#modal-bar"
ng-click="quickView(quickview)"><i class="fa fa-eye">
</i><span>Quick View</span></div>
</div>
This is my controller.js file
angular.module('myApp',[]).controller('filterController', function($scope) {
$scope.quickView = function quickView(id){
$.ajax({
type: 'GET',
url: 'assets/external/_modal.html',
data: id,
success: function (data) {
// Create HTML element with loaded data
$('body').append(data);
console.log('body append');
},
error:function(jqXHR,textStatus,exception){console.log('Exception:'+exception);}
});
}
$scope.venue = "India";
}
This is _modal.html
<div ng-controller="filterController">
<p>Hi. I live in {{venue}}</p>
</div>
How can I pass the controller scope to the external file _modal.html so that "I live in India" gets displayed instead of "I live in {{venue}}"?
Try angularjs way. Use uib modal. https://angular-ui.github.io/bootstrap
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope,$uibModal, $log, $document) {
$scope.animationsEnabled = true;
$scope.Venue = "India"; // declare venue
$scope.open = function (size, parentSelector) {
var parentElem = parentSelector ?
angular.element($document[0].querySelector('.modal-demo ' + parentSelector)) : undefined;
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
appendTo: parentElem,
resolve: {
values: function () {
return $scope.Venue; //we are passing venue as values
}
}
});
modalInstance.result.then(function () {
$scope.msg = "Submitted";
$scope.suc = true;
}, function(error) {
$scope.msg = 'Cancelled';
$scope.suc = false;
});
};
});
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope,$uibModalInstance, values) { // inject that resolved values
$scope.Venue= values; // we are getting & initialize venue from values
$scope.ok = function () {
$uibModalInstance.close('ok');
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl" class="modal-demo">
<br>
<form name="form" novalidate>
Type your venue : <input type="text" style="width:200px" class="form-control" name="name" ng-model="Venue" required><br>
<button type="button" ng-disabled="form.$invalid" class="btn btn-default" ng-click="form.$valid && open()">See Venue</button>
</form><br>
<p ng-hide="!msg" class="alert" ng-class="{'alert-success':suc, 'alert-danger':!suc}">{{msg}}</p>
</div>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title" id="modal-title">Your Details</h3>
</div>
<div class="modal-body" id="modal-body">
<p>The venue is <b>{{Venue }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="ok()">Submit</button>
<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>
</script>
</body>
</html>

angular bootstrap modal service not working

I created a common modal service in my application.
But it's not working somehow. Some small thing am missing on this plunker but am not able to figure out.
Based on passed parameter either it will open error-dialog or cancel-dialog.
Find PLUNKER here
Here is
JS
// create angular app
var validationApp = angular.module('validationApp', ['ui.bootstrap']);
// create angular controller
validationApp.controller('mainController', function($scope, ModalService) {
var vm = this;
// function to submit the form after all validation has occurred
vm.submitForm = function() {
// check to make sure the form is completely valid
if ($scope.userForm.$valid) {
alert('our form is amazing');
}
};
function openDialog() {
alert('why am not showing');
ModalService.openModal('Analysis Error', 'Complete Application Group configuration prior to running analysis.', 'Error');
}
});
//controller fot dialog
validationApp.controller('ErrorDialogCtrl',
function($uibModalInstance, message, title, callback) {
alert('sfdsfds');
var vm = this;
vm.message = message;
vm.onOk = onOk;
vm.onContinue = onContinue;
vm.onDiscard = onDiscard;
vm.callback = callback;
vm.title = title;
function onOk() {
$uibModalInstance.close();
}
function onContinue() {
$uibModalInstance.close();
}
function onDiscard() {
vm.callback();
$uibModalInstance.close();
}
});
// common modal service
validationApp.service('ModalService',
function($uibModal) {
return {
openModal: openModal
};
function openErrorModal(title, message, callback) {
$uibModal.open({
templateUrl: 'ErrorDialog.html',
controller: 'ErrorDialogCtrl',
controllerAs: 'vm',
backdrop: 'static',
size: 'md',
resolve: {
message: function() {
return message;
},
title: function() {
return title;
},
callback: function() {
return callback;
}
}
});
}
function openCancelModal(title, message, callback) {
$uibModal.open({
templateUrl: 'CancelDialog.html',
controller: 'ErrorDialogCtrl',
controllerAs: 'vm',
backdrop: 'static',
size: 'md',
resolve: {
message: function() {
return message;
},
title: function() {
return title;
},
callback: function() {
return callback;
}
}
});
}
function openModal(title, message, modalType, callback) {
if (modalType === "Error") {
openErrorModal(title, message, callback);
} else {
openCancelModal(title, message, callback);
}
}
}
);
Opening Dialog in HTML
<div class="col-sm-6">
<button type="submit" class="btn btn-primary" ng-click="openCancelDialog()">Open Cancel Dialog</button>
<button type="submit" class="btn btn-primary" ng-click="openErrorDialog()">Open Error Dialog</button>
</div>
Cancel Dialog HTML
<div>
<div class="modal-header">
<h3 class="modal-title">{{vm.title}}</h3>
</div>
<div class="modal-body">
<p ng-bind-html="vm.message"></p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="vm.onContinue()" id="continue">Continue</button>
<button class="btn btn-primary" ng-click="vm.onDiscard()" id="discard">Discard</button>
</div>
</div>
ErrorDiaog HTML
<div>
<div class="modal-header">
<h3 class="modal-title">{{vm.title}}</h3>
</div>
<div class="modal-body">
<p ng-bind-html="vm.message"></p>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="vm.onOk()">ok</button>
</div>
</div>
wrong in your js file, you need to declare function like below. you just copy these code and put it in your file then it will work fine.
NOTE: not ModalService.showModal, it should be ModalService.openModal
check your code here
$scope.openCancelDialog = function() {
alert('why am not showing CAncel');
ModalService.openModal('Analysis Error', 'I am Error Type', 'Error');
}
$scope.openErrorDialog = function() {
console.log('why am not showing Error');
ModalService.openModal('Analysis Error', 'I am cancel Type', 'Cancel');
}
i've created a new PLNKR here:
https://plnkr.co/edit/3RBJneSt7RCClrJ5Hba2?p=preview
$scope.submitForm = function() {
//check to make sure the form is completely valid
if ($scope.userForm.$valid) {
alert('our form is amazing');
}
};
$scope.openCancelDialog = function(){
//alert('why am not showing CAncel');
ModalService.openModal('Analysis Error', 'I am Error Type', 'Error');
}
$scope.openErrorDialog = function(){
//alert('why am not showing Error');
ModalService.openModal('Analysis Error', 'I am cancel Type', 'Cancel');
}

import excel data to database in angularjs

I am trying to read and insert excel file data to mysql database table using angularjs( front and) and codeigniter (back end).thanks in advance
included xlsx-reader.js
this is only the excel file read code it is not working.
HTML
<div ng-app="App">
<div ng-controller="PreviewController">
<div class='form-group'>
<label for='excel_file'>Excel File</label>
<button class="btn btn-link" type="file" ng-model="file"ngf-select ngf-change="importToExcel()">
<span class="glyphicon glyphicon-share"></span>ImportExcel
</button>
</div>
</div>
</div>
app.js
(function(undefined) {
App.factory("XLSXReaderService", ['$q', '$rootScope',
function($q, $rootScope) {
var service = function(data) {
angular.extend(this, data);
};
service.readFile = function(file, showPreview) {
var deferred = $q.defer();
XLSXReader(file, showPreview, function(data){
$rootScope.$apply(function() {
deferred.resolve(data);
});
});
return deferred.promise;
};
return service;
}
]);
}).call(this);
controller.js
angular.module('App').controller('PreviewController', function($scope, XLSXReaderService)
{
$scope.showPreview = false;
$scope.importToExcel= function(files) {
$scope.sheets = [];
$scope.excelFile = file[0];
XLSXReaderService.readFile($scope.excelFile, $scope.showPreview).then(function(xlsxData) {
$scope.sheets = xlsxData.sheets;
});
};
}