below is my first controller
.controller('configManagementCtrl', ['$scope', 'deConfigService', 'ngDialog', '$state', 'notificationService',
function ($scope, deConfigService, ngDialog, $state, notificationService) {
$scope.loadDetails = function () {
....
};
$scope.openModal = function () {
var newClassDialog = ngDialog.open({
template: 'views/modals/newClassModal.html',
closeByEscape: false,
controller: 'newClassController',
className: 'ngdialog-theme-default',
width: 600
});
newClassDialog.closePromise.then(function (data) {
console.log(data);
if (data.passBackData.value === 2) {
$scope.loadDetails();
// $state.go('app.config', {}, {reload: true, inherit: false});
// $scope.loadDetails();
}
});
};
}])
In my second controller am trying to send some data to my parent controller as shown below
.controller('newClassController', ['$scope', 'ngDialog', 'deConfigService', 'notificationService',
function ($scope, ngDialog, deConfigService, notificationService) {
$scope.classObj = {};
var passBackData = [];
$scope.cancel = function () {
passBackData.push({'closeVal': 1});
console.log(passBackData);
ngDialog.close(1, passBackData);
};
$scope.create = function (isFormValid) {
if (isFormValid) {
$scope.classObj.added_dt = (new Date()).toISOString();
$scope.classObj.class_id = 0;
deConfigService.createClass($scope.classObj, function (response) {
if (response.data) {
console.log(response.data);
passBackData.push(response.data.data);
notificationService.addSuccess('Class created successfully');
}
else {
notificationService.addError('Error!! Please try later');
}
});
ngDialog.close(1, 2);
}
};
}])
below is the ngdialog html. It has 2 textbox which am able to get data to my second controller but not able to send response back to first controller
<form ng-submit="create(form.$valid)" name="form" novalidate="">
<div class="form-flex ng-pristine ng-invalid ng-touched">
<div class="form-tile">
<label>Class name </label>
<input type="text" ng-model="classObj.name" name="form.name" placeholder="Enter the name of your class" required>
<label>Class description</label>
<textarea ng-model="classObj.description" name="form.description" placeholder="Enter a short description" rows="5" required></textarea>
</div>
</div>
<button type="submit" ng-click="submittedForm = true;" ng-disabled="form.$invalid" class="mat-raised-button-blue"> Create </button>
<button class="mat-raised-button" style="float:right; width:155px" ng-click="cancel();"> Cancel </button>
</form>
Am pushing some objects to the array and trying to send but not able to receive it from parent controller.
Where am doing wrong?
After a closer read of the documentation, it looks like you need to call .close() passing the id of the dialog and the value to return from the dialog's controller. In your parent controller the object passed back to your closePromise callback has id and value properties. You'll need to get whatever you're passing back via the value property (i.e. data.value.whateverYouAreReturning). Here is a simple example that returns an object with a single string property.
angular.module('app', ['ngDialog'])
.controller('ctrl', ($scope, ngDialog) => {
$scope.returnedValue = "";
$scope.openModal = function() {
var newClassDialog = ngDialog.open({
template: 'dialogTemplate',
closeByEscape: false,
controller: 'dialogCtrl',
className: 'ngdialog-theme-default',
width: 600
});
newClassDialog.closePromise.then(function(data) {
$scope.returnedValue = data.value.result;
});
};
})
.controller('dialogCtrl', ($scope, ngDialog) => {
var id = ngDialog.getOpenDialogs()[0];
$scope.returnValue = "";
$scope.close = () => {
ngDialog.close(id, { result: $scope.returnValue });
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-dialog/1.4.0/js/ngDialog.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-dialog/1.4.0/css/ngDialog.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-dialog/1.4.0/css/ngDialog-theme-default.min.css">
<div ng-app="app" ng-controller="ctrl">
<button ng-click="openModal()">Open Modal</button>
<p>Returned from dialog: {{ returnedValue }}</p>
<script type="text/ng-template" id="dialogTemplate">
<h1>ngDialog Sample</h1>
<p>
<label>Enter a value to return: </label>
<input type="text" ng-model="returnValue" />
</p>
<p><button ng-click="close()">Close</button></p>
</script>
</div>
This might work (can't test it unless you can share a plunker):
.controller('configManagementCtrl', ['$scope', 'deConfigService', 'ngDialog', '$state', 'notificationService',
function ($scope, deConfigService, ngDialog, $state, notificationService) {
$scope.loadDetails = function () {
....
};
$scope.openModal = function () {
$scope.newClassDialog = ngDialog.open({
template: 'views/modals/newClassModal.html',
closeByEscape: false,
controller: 'newClassController',
className: 'ngdialog-theme-default',
width: 600
});
$scope.newClassDialog.closePromise.then(function (data) {
console.log(data);
if (data.passBackData.value === 2) {
$scope.loadDetails();
// $state.go('app.config', {}, {reload: true, inherit: false});
// $scope.loadDetails();
}
});
};
}])
and in the other controller:
.controller('newClassController', ['$scope', 'ngDialog', 'deConfigService', 'notificationService',
function ($scope, ngDialog, deConfigService, notificationService) {
$scope.classObj = {};
var passBackData = [];
$scope.cancel = function () {
passBackData.push({'closeVal': 1});
console.log(passBackData);
$parent.$scope.newClassDialog.close(1, passBackData);
};
$scope.create = function (isFormValid) {
if (isFormValid) {
$scope.classObj.added_dt = (new Date()).toISOString();
$scope.classObj.class_id = 0;
deConfigService.createClass($scope.classObj, function (response) {
if (response.data) {
console.log(response.data);
passBackData.push(response.data.data);
notificationService.addSuccess('Class created successfully');
}
else {
notificationService.addError('Error!! Please try later');
}
});
$parent.$scope.newClassDialog.close(1, 2);
}
};
}])
Related
Hi I am developing angular js application. I am using ui-routing technique. I am facing issues in button click event. Below is my main.js file.
var app = angular.module('RoslpApp', ['pascalprecht.translate', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $urlRouterProvider, $translateProvider, $translatePartialLoaderProvider) {
$stateProvider.state('ForgotPassword', {
url: '/ForgotPassword',
templateUrl: 'ForgotPassword/ForgotPassword.html',
controller: 'ForgotPassword'
});
$stateProvider
.state('ForgotPassword.ResetPassword', {
url: '/ResetPassword',
templateUrl: 'ForgotPassword/ResetPassword.html',
controller: 'ResetPassword'
});
});
});
Below is my forgotpassword.html
<div class="container">
<div ui-view></div>
</div>
Here i am injecting ResetPassword.html.
Below is my ResetPassword.html
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
Above button does not work.
This is my Resetpasswordcontroller.
(function () {
angular.module('RoslpApp').controller('ResetPassword', ['$rootScope', '$translatePartialLoader', '$translate', function ($ResetPasswordService, $scope, $translatePartialLoader, $translate) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
})();
Resetpasswordservice.js
app.service("ResetPasswordService", function ($http, $state) {
alert("aaa");
this.ResetPassword = function () {
var url = '/api/projects/7';
return $http.post(url).then(function (response) {
return response.data;
});
}
});
$scope.ResetPassword is not working and i am not getting error also. Any help would be appreciated. Thank you.
I think your arguments are wrong, try to change it to something like this (corresponding arguments):
[
'$rootScope',
'ResetPasswordService',
'$scope',
'$translatePartialLoader',
'$translate',
function ($rootScope, $ResetPasswordService, $scope, $translatePartialLoader, $translate){
[...]
}
]
Your dependency injection order is wrong. Try this one:
(function () {
angular.module('RoslpApp').controller('ResetPassword', ['$scope', '$http', '$translatePartialLoader', '$translate', 'ResetPasswordService', function ($scope, $http, $translatePartialLoader, $translate, ResetPasswordService) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
$http.post('/api/projects/7').then(function (response) {
alert(JSON.stringify(response.data));
}, function (error) {
console.log(error);
});
}
}]);
})();
ResetPasswordService.js
angular.module('RoslpApp').service("ResetPasswordService", function ($http, $state) {
alert("aaa");
this.ResetPassword = function () {
var url = '/api/projects/7';
return $http.post(url).then(function (response) {
return response.data;
});
}
});
var myApp = angular.module("myApp", []);
myApp.controller("myController", ['$rootScope' , function( $scope){
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller= "myController">
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
</div>
</body>
var myApp = angular.module("myApp", []);
myApp.controller("myController", ['$rootScope' , function( $scope){
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
<!-- begin snippet: js hide: false console: true babel: false -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller= "myController">
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller= "myController">
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
</div>
</body>
There may be problme while passing the dependency to controller in passing the arguments to callback.I tried simple way with one arguments.its work to me.Check it
Change your code like below. Your order and reference is wrong.
angular.module('RoslpApp').controller('ResetPassword', ['$rootScope','$scope', '$translatePartialLoader', '$translate','ResetPasswordService', function ($rootScope, $scope, $translatePartialLoader, $translate,ResetPasswordService) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
Change you ResetPassword.html code as following:
<div class="button-container">
<input type="button" value="Submit" id="input-submit" ng-click="ResetPassword()" />
</div>
Also, edit you controller as the problem is due to incorrect dependencies order. You should rewrite as:
(function () {
angular.module('RoslpApp').controller('ResetPassword', ['$ResetPasswordService','$scope', '$translatePartialLoader', '$translate', function ($ResetPasswordService, $scope, $translatePartialLoader, $translate) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
})();
If I Create/Update/Delete Values in my Array the ng-table is not Updating the Data. I need to do a window.location.reload() for that but thats not very "beautifull". Shouldnt in Angularjs through 2Way DataBinding and Automatic $apply Cycle it do it by it self?
My Code to Review maybe I forgot something:
'use strict';
(function() {
class TranslationsComponent {
constructor($http, $scope, $uibModal) {
this.$http = $http;
this.$scope = $scope;
this.$uibModal = $uibModal;
this.langV = [];
}
$onInit() {// getting my Datas
this.$http.get('/api/dict_keys/all/' + 1 + '/' + 1)
.then(response => {
this.langV = response.data;
});
}
// For Example Deleting something with a Modal
// Delete Modal
deleteKey(selectedKey) {
this.$uibModal.open({
scope: this.$scope,
templateUrl: 'delete.html',
controller: ['$scope', '$uibModalInstance', '$http', 'selectedKey',
function($scope, $uibModalInstance, $http) {
$scope.selectedKey = selectedKey;
this.$http = $http;
$scope.close = function() {
$uibModalInstance.dismiss();
};
$scope.delete = () => {
this.$http.delete('/api/dict_keys/' + selectedKey._id)
.then(() => {
//window.location.reload();
//what can i instead of realod do?
toastr.success('The Key is successfully Deleted');
$uibModalInstance.close();
});
};
}
],
resolve: {
selectedKey: () => selectedKey
}
});
}
/* ----------------------------------------- */
angular.module('euconDictionaryApp')
.component('translations', {
templateUrl: 'app/translations/translations.html',
controller: TranslationsComponent
});
})();
In my .html its a Simple ng-repeat showing everything, in short:
<tr dir-paginate="v in $ctrl.langV |itemsPerPage: 10">
<td>
{{v.Name}}
</td>
<td>
<!-- Delete Key Button -->
<button type="button" class="btn btn-default" ng-click="$ctrl.deleteKey(v)">
</button>
</td>
Looks like you will need to update 'this.langV' array after delete or update in order to see the update. You can use javascript splice method to remove an item from array.
After delete you can use
this.langV.splice(this.langV.indexOf(v), 1)
After update you can update the item like
this.langV[index] = updateItem
I have two directives that reference the same parent variable. The first directive is a dropdown. The second directive is a table. What I'm trying to accomplish is this: when a selection is made on the dropdown, the parent variable will change. The second directive using $scope.$watch will detect this change and load the data to the table. Problem is that the second directive is not detecting the change. I'm not understanding why.
// home.html
<div>
<directive-one testid="home.changevalue"></directive-one>
<br />
<directive-two testid="home.changevalue"></directive-two>
</div>
// search.directive.html
<div style="margin-top:5px;margin-left:25px;">
<div class="row" style="margin-bottom:10px;">
<label for="searchoptions" style="margin-left:15px;">Food Items</label>
<br />
<select style="margin-left:15px;" name="searchoptions" id="searchoptions1" ng-model="searchFoodItems.fooditemid" ng-change="searchFoodItems.onSelectionChange()">
<option value="">Select ...</option>
<option ng-repeat="fooditem in searchFoodItems.fooditems" value="{{fooditem.entryid}}">{{fooditem.itemdesc}}</option>
</select>
<span>Food Item ID - {{searchFoodItems.fooditemid}}</span>
</div>
</div>
// list.directive.html
<div style="margin-top:5px;margin-left:30px;">
<table class="table table-responsive">
<thead>
<tr>
<th>ID</th>
<th>Description</th>
<th>Discount</th>
</tr>
</thead>
<tfoot></tfoot>
<tbody>
<tr ng-repeat="row in listFoodItems.fullitemdescs">
<td>{{row.EntryId}}</td>
<td>{{row.ItemDesc}}</td>
<td>{{row.ItemDisc}}</td>
</tr>
</tbody>
</table>
</div>
JS -
// home.js
(function () {
'use strict';
angular
.module(testConstants.generateName(testConstants.appModule, testConstants.NAMETYPES.module))
.controller(testConstants.generateName('home', testConstants.NAMETYPES.controller), home);
home.$inject = ['$scope', '$location', '$routeParams', '$q', '$window', 'logger', 'dataservice'];
function home($scope, $location, $routeParams, $q, $window, logger, dataservice) {
var home = this;
home.changevalue = '';
}
})();
// search.js
(function () {
'use strict';
angular
.module(testConstants.generateName(testConstants.appModule, testConstants.NAMETYPES.module))
.directive(testConstants.generateName('directiveOne', testConstants.NAMETYPES.directive), searchFoodItems);
searchFoodItems.$inject = ['dataservice', 'logger'];
function searchFoodItems(dataservice, logger) {
var sfi = {
restrict: 'E',
templateUrl: 'App/search/search.directive.html',
scope: {
fooditemid: '='
},
link: function (scope, element, attrs, controller) { },
controller: searchFoodItemsController,
controllerAs: 'searchFoodItems'
}
return sfi;
}
searchFoodItemsController.$inject = ['$scope', 'dataservice', 'logger'];
function searchFoodItemsController($scope, dataservice, logger) {
var search = this;
search.fooditemid = '';
search.fooditems = [];
search.onSelectionChange = function () {
$scope.fooditemid = search.fooditemid;
}
activate();
function activate() {
loadFoodItems();
}
function loadFoodItems() {
return dataservice.getFoodItems().then(function (result) {
search.fooditems = result;
logger.log("search.directive.js = getFoodItems loaded");
});
}
}
})();
// list.js
(function () {
'use strict';
angular
.module(testConstants.generateName(testConstants.appModule, testConstants.NAMETYPES.module))
.directive(testConstants.generateName('directiveTwo', testConstants.NAMETYPES.directive), listFoodItems);
listFoodItems.$inject = ['dataservice', 'logger'];
function listFoodItems(dataservice, logger) {
var lfi = {
restrict: 'E',
templateUrl: 'App/list/list.directive.html',
scope: {
fooditemid: '='
},
link: function (scope, element, attrs, controller) { },
controller: listFoodItemsController,
controllerAs: 'listFoodItems'
}
return lfi;
}
listFoodItemsController.$inject = ['$scope', '$q', 'dataservice', 'logger'];
function listFoodItemsController($scope, $q, dataservice, logger) {
var list = this;
list.fullitemdescs = [];
activate();
function watchFoodItem() {
$scope.$watch("$scope.fooditemid", function (value) {
$q.all([load(value)]).then(function () { logger.log('list.directive.js - fooditemid changed'); });
});
}
function activate() {
watchFoodItem();
load($scope.fooditemid);
}
function load(id) {
if (id === '') {
loadFoodItems();
}
else {
loadFoodItem(id);
}
}
function loadFoodItems() {
return dataservice.getFoodDescDiscs().then(function (result) {
list.fullitemdescs = result;
logger.log("list.directive.js = getFoodItems loaded");
});
}
function loadFoodItem(id) {
return dataservice.getFoodDescDisc(id).then(function (result) {
list.fullitemdescs = result;
logger.log("list.directive.js = getFoodItem loaded");
});
}
}
})();
Remove function and $scope from watcher.
//function watchFoodItem() {
$scope.$watch("fooditemid", function (value) {
$q.all([load(value)]).then(function () { logger.log('list.directive.js - fooditemid changed'); });
});
// }
I'm writing a controller. This controller has to communicate with an other controller. But I don't know is it posible?
HTML:
<div data-ng-app="TestApp">
<div data-ng-controller="menuCtrl">
<ul>
<li> <a data-ng-click="Click()">
MenĂ¼1</a>
</li>
</ul>
</div>
<div data-ng-controller="pageCtrl">
<hr/>
<button data-ng-click="getText()">GetText</button>
<br/>
<strong data-ng-model="boldText"> {{boldText}}</strong>
</div>
JS:
var app = angular.module('TestApp', []);
app.controller('menuCtrl', function ($rootScope, $scope) {
$scope.Click = function () {
//???
};
})
.controller('pageCtrl', function ($rootScope, $scope) {
$scope.getText = function () {
$scope.boldText = 'tst';
};
});
I repaired sample on JSfiddle:sample
You can easily achieve that with broadcasting:
var app = angular.module('TestApp', []);
app.controller('menuCtrl', function ($rootScope, $scope) {
$scope.Click = function () {
$scope.$broadcast('MyClickEvent', {
someProp: 'Clicking data!' // send whatever you want
});
};
})
.controller('pageCtrl', function ($rootScope, $scope) {
$scope.getText = function () {
$scope.boldText = 'tst';
};
$scope.$on('MyClickEvent', function (event, data) {
console.log(data); // 'Data to send'
});
});
Using the events broadcast, we can pass the value form one controller to another
app.controller('menuCtrl', function ($rootScope, $scope) {
$scope.Click = function () {
var valueToPass = "value";
$rootScope.$broadcast('eventMenuCtrl', valueToPass);
};
})
.controller('pageCtrl', function ($rootScope, $scope) {
$scope.getText = function () {
$scope.boldText = 'tst';
};
$scope.$on('eventMenuCtrl', function(event, value) {
$scope.boldText = value;
})
});
http://jsfiddle.net/q2yn9jqv/4/
I want to call a method from one controller to another controller. There are two controllers named "header" and "mainContent". Need to call a "trigger method" in the "header Controller", After the success call of "result method" in the mainController.
If that method called that should hide that paragraph.
<div ng-controller="header">
<p ng-show="msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($scope, $location) {
$scope.msg=true;
$scope.trigger= function(data) { //This method should be called after the result method called in the mainContent Controller
$scope.$on('UPDATE_CHILD', function() {
if(data)
$scope.msg=false;
});
}
});
// mainContent controller
module.controller('mainContent', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$scope.$broadcast('UPDATE_CHILD');
//From here I want to call trigger method of header controller
}
})
};
});
did u try this?
module.controller('header', ['$scope', '$location', '$rootScope', function ($scope, $location, $rootScope) {
$scope.msg=true;
$scope.trigger= function(data) {
if(data)
$scope.msg=false;
};
$rootScope.$on('event:fire', $scope.trigger);
}]);
// mainContent controller
module.controller('mainContent', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.$broadcast('event:fire');
}
})
};
}]);
You can use $rootScope like:
<div ng-controller="header">
<p ng-show="$root.header.msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($rootScope,$scope, $location) {
$rootScope.header.msg = true;
});
// mainContent controller
module.controller('mainContent', function ($rootScope,$scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.header.msg = true;
}
})
};
});
in the follwoing code you can see headerController is calling alert in mainController
myApp = angular.module("myApp",[]);
myApp.service("myService", function(){
showAlertBool = false;
return {
showAlert: function (value) {
showAlertBool = value;
},
canShowAlert: function () {
return showAlertBool;
}
}
});
myApp.controller("headerController", function($scope, myService){
console.log(myService);
$scope.clickHandler = function(){
myService.showAlert(true);
}
});
myApp.controller("mainController", function($scope, myService){
console.log(myService);
$scope.getServiceValue = function(){
return myService.canShowAlert();
}
$scope.$watch("getServiceValue()", function(newValue, oldValue){
if(newValue === true && newValue !== oldValue){
myService.showAlert(false);
alert("I can show Alert now!!!");
}
});
});
For a working code you can go here