I'm having some issues with the flow of my application. I'm trying to refresh a list when a new item has been created using a modal.
This is what the logic should be:
Hit new group button Modal shows up,
fill form Submit form, data is sent over to the service
Service creates the new group and calls the getGroup()
getGroups retrieves the new list of groups, the service resolves
After the service is done I need to set variables in my main ctrl so the DOM reflects the new change
HTML:
<div class="topPanel">
<div class="topRow">
<label for="entityDropDown">Select a Group:</label>
<select id="entityDropDown" ng-model="selectedGroup" ng-options="group as group.name for group in groups" ng-change="getGroupInfo(selectedGroup)"></select>
<button type="button" class="delGroupBtn btn-danger" ng-disabled="!selectedGroup" ng-click="deleteGroup()">✖</button>
<button type="button" class="delGroupBtn btn-success" ng-click="newGroup()">New Group</button>
</div>
<div class="userGroups" ng-show="selectedGroup">
<div>
<label for="entityAvailable">Available Users</label>
<select id="entityAvailable" multiple ng-model="selectedAvailableUsers" ng-options="u.name for u in availableUsers | orderBy: 'name'"></select>
</div>
<div id="moveButtons">
<button type="button" ng-disabled="!selectedGroup || availableUsers.length === 0 || selectedAvailableUsers.length === 0" ng-click="manageGroup(true)">Add to Group</button>
<button type="button" ng-disabled="!selectedGroup || assignedUsers.length == 0 || selectedAssignedUsers.length === 0" ng-click="manageGroup(false)">Remove from Group</button>
</div>
<div>
<label for="entityAssigned">Users In Group</label>
<select id="entityAssigned" multiple ng-model="selectedAssignedUsers" ng-options="u.name for u in assignedUsers | orderBy:'name'"></select>
</div>
</div>
<br class="clearfix" />
</div>
groupCtrl:
$scope.newGroup = function (){
var d = $q.defer();
var modalForm = '/Style%20Library/projects/spDash/app/partials/newGroup.html';
var modalInstance = $modal.open({
templateUrl: modalForm,
backdrop: true,
windowClass: 'modal',
controller: newGroupCtrl,
resolve:{
newGroup:function (){
return $scope.newGroup;
}
}
});
$scope.selectedGroup = false;
$scope.groups = groupService.getGroups();
d.resolve();
return d.promise;
};
/*At first I wanted to set newGroups to return a promise and then manipulate the $scope elements.But I got error then() is not a function of $scope.newGroup so I had to move the scope elements up into the function but now it runs before the service is even done. */
/*$scope.newGroup.then(function(){
$scope.selectedGroup = false;
$scope.groups = groupService.getGroups();
},
function(){
console.log('failed to create new group');
});*/
Modal newGroupCtrl:
var newGroupCtrl = function ($scope, $modalInstance, groupService){
$scope.newGroup = {};
$scope.submit = function(){
console.log('creating new group');
console.log($scope.newGroup);
$modalInstance.close($scope.newGroup);
}
$scope.cancel = function (){
$modalInstance.dismiss('Cancelled group creation');
};
$modalInstance.result.then(function (newGroup){
groupService.createGroup(newGroup);
}, function (reason){
console.log(reason);
});
}
createGroup Service function:
var createGroup = function (newGroup) {
var deferred = $q.defer();
var currentUser = $().SPServices.SPGetCurrentUser({
fieldName: "Name",
debug: false
});
var promise = $().SPServices({
operation: "AddGroup",
groupName: newGroup.name,
description: newGroup.desc,
ownerIdentifier: currentUser,
ownerType: "user",
defaultUserLoginName: currentUser,
})
promise.then(function (){
console.log('new group created');
getGroups();
deferred.resolve();
},
function(){
console.log('failed to create new group');
deferred.reject();
});
return deferred.promise;
}
Problem: How do I get the main controller to run functionsAFTER the createGroup service function has finished and returned it's promise?
For example, once the modal calls createGroup service function and that function updates my user list, I need to set these elements in the main groupCtrl:
$scope.selectedGroup = false;
$scope.groups = groupService.getGroups();
Related
I am facing an issue while using mdDialog confirm from angularJS material design. I am using the confirm box to ask a user for his choice to continue or confirm, If the user confirms the API will take the value and return the returns or else return, however my API is still being called even if the user does not confirm anything. I was able to get around the issue by using normal confirm and alert box but would be thankful if some body can suggest me a fix. I have looked into promises but could not figure how to implement it in my code. Here is a snippet of my code
if ($scope.options.selected[i].field === "displayInterval") {
data.aggregations = "date:" + $scope.options.selected[i].value.toString();
if (data.aggregations === 'date:hour' || 'date:minute') {
var confirm = $mdDialog.confirm()
.title('Some of the providers you selected do not support this display interval.')
.textContent('Continue with only sources that support by hour or minute charting.')
.ok('Yes')
.cancel('No');
$mdDialog.show(confirm).then(function() {
$scope.aggs = data.aggregations;
}, function() {
return;
});
} else {
$scope.aggs = data.aggregations;
}
}
rts.doSearch(data).then(function(response){
$('.lineChart').show();
if (response.status == 500 || response.status == 404 || response.status == 401) {
alert("Error:" + response.message);
return;
}
loadAggregation(response.provider_results, data.query);
So here rts.doSearch(data) is the call being made to the API which is getting executed regardless of the if condition before it.
I use something similar but it's ui instead of Material, anyway i believe it could give the clues to make it work.
app.controller('prioridade', function($scope, $filter, $uibModal) {
$scope.prioridades = response.data;
$scope.mymodal={};
$scope.openmymodal = function(msize, mtimeout, mbackdrop, mclass, mresponse){ /*this has some variables to make it dynamic*/
$scope.mymodal.size = msize!=''?msize:'md';
$scope.mymodal.timeout = mtimeout!=''?mtimeout:0;
$scope.mymodal.backdrop = mbackdrop!=''?mbackdrop:true;
$scope.mymodal.mclass = mclass!=''?mclass:'btn-success';
$scope.mymodal.mresponse = mresponse!=''?mresponse:'no';/*aguardar por resposta yes or no*/
var modalInstance = $uibModal.open({
animation: true, ariaLabelledBy: 'modal-title', ariaDescribedBy: 'modal-body',
templateUrl: 'myMainModal.html', controller: 'ModalInstanceCtrl', keyboard: true,
controllerAs: '$ctrl', size: $scope.mymodal.size, backdrop: $scope.mymodal.backdrop,/*true or 'static'*/
resolve: {mymodal: function(){return $scope.mymodal;}} /*to pass the variables to the modal*/
});
modalInstance.result.then(function(result) {
$scope.myresult = result;
if($scope.myresult.results=='OK'){
/*do what ever you want*/
} else { /*if canceled*/}
});
};
/*here is where i call the modal function*/
$scope.resetPSW = function(user) {
$scope.mymodal.header='! Atenção está prestes a Apagar a Psw do User!';
$scope.mymodal.body='<div class="col-md-12 col-sm-12 col-xs-12">** Tem a certeza que pretende apagar a Psw deste user? **</div>';
$scope.mymodal.post=user; $scope.openmymodal('md', 1, true, 'btn-danger', 'yes');
};
});
app.controller('ModalInstanceCtrl', function ($uibModalInstance, mymodal, $timeout, $sce) {
var $ctrl = this; $ctrl.mymodal = mymodal; $ctrl.mymodal.body = $sce.trustAsHtml($ctrl.mymodal.body);
switch($ctrl.mymodal.timeout){
case 0, 1:
$ctrl.ok = function(){$ctrl.mymodal['results'] = 'OK'; $uibModalInstance.close($ctrl.mymodal);};
$ctrl.cancel = function(){$uibModalInstance.dismiss('cancel');};
break;
default:
promise = $timeout(function(){$uibModalInstance.dismiss('cancel');}, 3000);
$ctrl.ok = function(){$ctrl.mymodal['results'] = 'OK'; $timeout.cancel(promise); $uibModalInstance.close($ctrl.mymodal);};
$ctrl.cancel = function(){$timeout.cancel(promise); $uibModalInstance.dismiss('cancel');};
break;
};
});
and the HTML
<script type="text/ng-template" id="myMainModal.html">
<div class="modal-header" ng-class="$ctrl.mymodal.mclass">
<h3 class="modal-title" id="modaltitle">{{$ctrl.mymodal.header}}</h3>
</div>
<div class="modal-body" id="modalbody" ng-bind-html="$ctrl.mymodal.body"></div>
</br>
<div class="modal-footer" id="modalfooter" ng-show="$ctrl.mymodal.timeout<=2">
<button class="btn btn-primary" type="button" ng-click="$ctrl.ok()">OK</button>
<button class="btn btn-warning" type="button" ng-click="$ctrl.cancel()" ng-show="$ctrl.mymodal.timeout==1">Cancel</button>
</div>
</script>
I have the following code and I have tried just bout everything to return a promise that would work with the directive. I have even tried returning the response data and return $q.when(data) and nothing. Ive tried reading on promises and this one is a bit different then Ive read. Something I'm missing?
myApp.controller('smsCtrl', function($scope){
$scope.sendSMS = function(){
let sms = {'number': $scope.number ,'message': $scope.message};
serviceNameHere.sendSMS(sms).then(function(response){
$scope.smsSuccessMsg = "Message Sent Successfully";
}, function(response){
$scope.smsErrorMsg = response.data['message'];
});
};
})
myApp.directive('onClickDisable', function() {
return {
scope: {
onClickDisable: '&'
},
link: function(scope, element, attrs) {
element.bind('click', function() {
element.prop('disabled',true);
scope.onClickDisable().finally(function() {
element.prop('disabled',false);
})
});
}
};
});
The following html
<div ng-controller="smsCtrl">
<-- field inputs here --></-->
<button type="button" class="btn btn-primary" on-click-disable="sendSMS()">SEND</button>
</div>
JSfiddle Example
There is no need to have a special directive for this. Simply use ng-disabled and ng-click:
<div ng-controller="smsCtrl">
<!-- field inputs here -->
<button ng-click="sendSMS()" ng-disabled="pendingSMS">
SEND
</button>
</div>
In the controller:
myApp.controller('smsCtrl', function($scope, serviceNameHere){
$scope.sendSMS = function(){
let sms = {'number': $scope.number ,'message': $scope.message};
$scope.pendingSMS = true;
serviceNameHere.sendSMS(sms).then(function(response){
$scope.smsSuccessMsg = "Message Sent Successfully";
}, function(response){
$scope.smsErrorMsg = response.data['message'];
}).finally(function() {
$scope.pendingSMS = false;
});
};
})
When the SMS message starts, the controller sets the pendingSMS flag to disable the Send button. When the service completes, the flag is reset and the button is re-enabled.
I have this problem in my app, when I use slice to remove the user from the list. However, it does not remove from the list. I am getting the user with a API url call. But for some reason, it does not remove the user from the list. Please, have a look at my code. If, you guys want the full code, I have put it in my github. I hope we both can solve this. Thank you in advance.
Here is my code:
<div ng-controller="MyCtrl">
<div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">
<a class="back" href="#/lawyer">Back</a>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>
<a class="delete" ng-click="confirmClick(); confirmedAction(person);" confirm-click>Confirm</a>
<div class="people-view">
<h2 class="name">{{person.firstName}}</h2>
<h2 class="name">{{person.lastName}}</h2>
<span class="title">{{person.email}}</span>
<span class="date">{{person.website}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
<br>
<b>Website:</b>
<input type="text" ng-model="person.website">
<br>
</fieldset>
</form>
</div>
</div>
</div>
App.js
var app = angular.module("Portal", ['ngRoute', 'ui.bootstrap' ]);
app.controller('MyCtrl', function($scope, $window) {
$scope.inactive = true;
$scope.confirmedAction = function (lawyer) {
$scope.$apply(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
});
};
});
app.directive('confirmClick', ['$q', 'dialogModal', function($q, dialogModal) {
return {
link: function (scope, element, attrs) {
// ngClick won't wait for our modal confirmation window to resolve,
// so we will grab the other values in the ngClick attribute, which
// will continue after the modal resolves.
// modify the confirmClick() action so we don't perform it again
// looks for either confirmClick() or confirmClick('are you sure?')
var ngClick = attrs.ngClick.replace('confirmClick()', 'true')
.replace('confirmClick(', 'confirmClick(true,');
// setup a confirmation action on the scope
scope.confirmClick = function(msg) {
// if the msg was set to true, then return it (this is a workaround to make our dialog work)
if (msg===true) {
return true;
}
// msg can be passed directly to confirmClick('Are you sure you want to confirm?')
// in ng-click
// or through the confirm-click attribute on the
// <a confirm-click="Are you sure you want to confirm?"></a>
msg = msg || attrs.confirmClick || 'Are you sure you want to confirm?';
// open a dialog modal, and then continue ngClick actions if it's confirmed
dialogModal(msg).result.then(function() {
scope.$eval(ngClick);
});
// return false to stop the current ng-click flow and wait for our modal answer
return false;
};
}
}
}])
/*
Modal confirmation dialog window with the UI Bootstrap Modal service.
This is a basic modal that can display a message with yes or no buttons.
It returns a promise that is resolved or rejected based on yes/no clicks.
The following settings can be passed:
message the message to pass to the modal body
title (optional) title for modal window
okButton text for YES button. set false to not include button
cancelButton text for NO button. ste false to not include button
*/
.service('dialogModal', ['$modal', function($modal) {
return function (message, title, okButton, cancelButton) {
// setup default values for buttons
// if a button value is set to false, then that button won't be included
cancelButton = cancelButton===false ? false : (cancelButton || 'No');
okButton = okButton ===false ? false : (okButton || 'Yes');
// setup the Controller to watch the click
var ModalInstanceCtrl = function ($scope, $modalInstance, settings) {
// add settings to scope
angular.extend($scope, settings);
// yes button clicked
$scope.ok = function () {
// alert("Lawyer is confirmed");
$modalInstance.close(true);
};
// no button clicked
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
// open modal and return the instance (which will resolve the promise on ok/cancel clicks)
var modalInstance = $modal.open({
template: '<div class="dialog-modal"> \
<div class="modal-header" ng-show="modalTitle"> \
<h3 class="modal-title">{{modalTitle}}</h3> \
</div> \
<div class="modal-body">{{modalBody}}</div> \
<div class="modal-footer"> \
<button class="btn btn-primary" ng-click="ok()" ng-show="okButton">{{okButton}}</button> \
<button class="btn btn-warning" ng-click="cancel()" ng-show="cancelButton">{{cancelButton}}</button> \
</div> \
</div>',
controller: ModalInstanceCtrl,
resolve: {
settings: function() {
return {
modalTitle: title,
modalBody: message,
okButton: okButton,
cancelButton: cancelButton
};
}
}
});
// return the modal instance
return modalInstance;
}
}])
app.config(function ($routeProvider) {
$routeProvider
.when("/lawyer", {
controller: "HomeController",
templateUrl: "partials/home.html"
})
.when("/lawyer/:id", {
controller: "LawyerController",
templateUrl: "partials/about.html"
})
.otherwise({
redirectTo: '/lawyer'
});
});
But the element is getting deleted from list right?
If yes then, Try this :
$scope.confirmedAction = function (lawyer) {
$scope.$apply(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
});
});
Or
$scope.confirmedAction = function (lawyer) {
$timeout(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$state.go($state.current, {}, {reload: true});
// $window.location.href = '#/lawyer';
},1100);
});
The problem is that you don't get the index from IndexOf when you using it on an array of objects like you do. Read more about the IndexOf here.
Instead, use map and then use IndexOf on that
Try it like this:
$scope.confirmedAction = function (lawyer) {
var index = $scope.userInfo.lawyers.map(function(e) { return e.id; }).indexOf(lawyer.id);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
};
And also, the controller changes will by default be detected by the digest loop of angular so no need to use $scope.$apply.
Also, simplifyed your plunker with the basic get array list and remove function. Use that to build your way forvered
https://plnkr.co/edit/w6NuVLcqzc5Rjs7L6Cox?p=preview
I have a page employee.html with a list of dependents and for each row (li) an inner button with the directive ng-click="editDependent({{dependent.id}})". That button tries to call a modal box.
The employee.html is loaded in a ui_view div from an index.html
I saw that each button in view source with chrome are correctly bound ng-click="editDepedent(1)" and so on.
But at the same time I have an error
angular.min.js:118 Error: [$parse:syntax] http://errors.angularjs.org/1.5.8/$parse/syntax?p0=%7B&p1=invalid%20key&p2=11&p3=editDependent(%7B%7Bdependent.id%7D%7D)&p4=%7Bdependent.id%7D%7D)
I'm trying to pass my dependent id to my modal and the previous scope also that contains the info about the employee. So how can I achieve this parameter passing?
This is my main controller
app.controller('EmployeeController', function ($scope, $stateParams, $uibModal, EmployeeService) {
if($stateParams.id){
EmployeeService.getEmployee($stateParams.id).then(function(employee){
$scope.employee = employee;
EmployeeService.setCurrentEmployee(employee);
});
}
$scope.editDependent = function(id){
if(id){
$scope.dependentid = id;
}
var uibModalInstance = $uibModal.open({
templateUrl : 'modal_dependent.html',
controller : 'DependentController',
scope: $scope
});
return uibModalInstance;
}
});
This is my dependent controller to catch the value
app.controller('DependentController', function($scope, $uibModal, $uibModalInstance, $stateParams, EmployeeService){
//Following line does not work because it gets the ID of employee which is passed by querystring
//var dependentID = $stateParams.id;
if($scope.dependentid){
var currentEmployee = EmployeeService.getCurrentEmployee();
//find the current dependent
for(var i = 0; i < currentEmployee.dependents.length; i++){
//*****************************************************
//Hardcoding 1 to test the dependent number 1 but it should be the dependent id parameter
if(currentEmployee.dependents[i].id == 1){
$scope.dependent = currentEmployee.dependents[i];
break;
}
}
}else{
$scope.dependent = { id : 0 };
}
$scope.editableDependent = angular.copy($scope.dependent);
//Submit button in modal
$scope.submitDependent = function(){
DependentService.saveDependent($scope.editableDependent);
$scope.dependent = angular.copy($scope.editableDependent);
$uibModalInstance.close();
}
});
UPDATE
employee.html
<form name="employee_form">
<div>
<h1> {{employee.name}} </h1>
<h3>Dependents</h3>
<button class="btn bgcolor-rb-main" x-ng-click="editDependent(0)">
Add new
</button>
<ul class="list-inline">
<li x-ng-repeat="dependent in employee.dependents">
<button x-ng-click="editDependent({{dependent.id}})">
Edit
</button><br>
<div>{{dependent.name}}</div>
</li>
</ul>
</div>
</form>
This is my modal_dependent.html
<div class="modal-header">
<h4>Dependent</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" id="txtName" x-ng-model="editableDependent.name" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" x-ng-click="discardChanges()">Discard</button>
<button type="submit" class="btn btn-primary" x-ng-click="submitDependent()">Save</button>
</div>
UPDATE
I changed my controller to initialize before $scope.dependent
app.controller('DependentController', function($scope, $uibModal, $uibModalInstance, $stateParams, EmployeeService){
//Following line does not work because it gets the ID of employee which is passed by querystring
//var dependentID = $stateParams.id;
$scope.dependent = { id : 0 };
if($scope.dependentid){
var currentEmployee = EmployeeService.getCurrentEmployee();
//find the current dependent
for(var i = 0; i < currentEmployee.dependents.length; i++){
//*****************************************************
//Hardcoding 1 to test the dependent number 1 but it should be the dependent id parameter
if(currentEmployee.dependents[i].id == 1){
$scope.dependent = currentEmployee.dependents[i];
break;
}
}
}
$scope.editableDependent = angular.copy($scope.dependent);
//Submit button in modal
$scope.submitDependent = function(){
DependentService.saveDependent($scope.editableDependent);
$scope.dependent = angular.copy($scope.editableDependent);
$uibModalInstance.close();
}
});
SOLVED
My button changed from this
<button x-ng-click="editDependent({{dependent.id}})">Edit</button>
To this
<button x-ng-click="editDependent(dependent.id)">Edit</button>
i think there is parsing error you have to define
$scope.dependentid = {};
before using it,
or otherwise you can use it as a model (if you are submitting a form on frontend like this)
<input type="hidden" ng-model="dependentid" />
it will be better to understand for me if you edit the code and add some frontend html
I have table with item list and modal window where i can change drug properties. When properties changed that drug have to remove from that list. But it's didn't remove.
Modal window:
$modal.open({
templateUrl:'app/interactions/partials/modals/resolveDrug.html',
controller: 'DrugsListController',
scope: $scope
}).result.then(function(data){
var index = _.findIndex($scope.drugs, {_id: data._id});
$scope.drugs.splice(index,1);
}
i think element didn't remove 'cause when i open modal window i create copy of my scope and then work with copy..
On that form i have refresh button that refresh all list.
$scope.refresh= function() {
$scope.drugs = UnresolvedDrugsService.query();
};
and it's didn't work too. I think it happens because i work with copy too.
Okey, i try to emit some event
$modal.open({
templateUrl:'app/interactions/partials/modals/resolveDrug.html',
controller: 'DrugsListController',
scope: $scope
}).result.then(function(data){
var index = _.findIndex($scope.drugs, {_id: data.data._id});
$rootScope.$emit('refreshDrug', index);
}
$rootScope.$on('refreshDrug', function(index){
$scope.drugs = [];
$scope.drugs.splice(index,1);
// $scope.drugs= UnresolvedDrugsService.query();
});
And it's not working.
Can you help me and describe what i doing wrong, thx!
UPD
modal window html
<form role="form" name="resolveDrugForm" ng-submit="saveResolvedDrug(drug) && $close(drug)">
........{some code, input's and label}......
<input type="submit" class="btn btn-primary" value="{{'COMMON.SAVE' | translate}}"/>
<button type="button" class="btn btn-default" ng-click="$dismiss()" >{{'COMMON.CANCEL' | translate}}</button>
code of ng-repeat
<tr ng-repeat="drug in drugs" ng-click="resolveDrug($index)">
<td>{{drug.productName || drug.description }}</td>
<td>{{drug.aiccode }}</td>
</tr>
and all method of controller:
$rootScope.$on('refreshDrug', function(index){
// $scope.drugs = [];
$scope.drugs.splice(index,1);
// $scope.drugs= UnresolvedDrugsService.query();
});
$scope.drugs= UnresolvedDrugsService.query();
$scope.refresh= function() {
$scope.drugs= UnresolvedDrugsService.query();
};
$scope.spliceEl = function(data){
var index = _.findIndex($scope.drugs, {_id: data._id});
$scope.drugs.splice(index,1);
return true;
};
$scope.saveResolvedDrug = function(drug){
DrugsService.addResolvedDrug(drug).then(function(data){
var index = _.findIndex($scope.drugs, {_id: data.data._id});
if(data.data.ingredients && data.data.ingredients.length > 0){
data.data.ingredients = JSON.parse(data.data.ingredients);
}
$scope.drugs.splice(index,1);
return true;
});
return true;
};
$scope.resolveDrug=function(index){
$scope.drug={};
var drugs = $scope.drugs;
$scope.drug=angular.copy($scope.drugs[index]);
var scope=$scope;
$modal.open({
templateUrl:'app/interactions/partials/modals/resolveDrug.html',
controller: 'DrugsListController',
scope: $scope
}).result.then(function(data){
console.log($scope.drugs);
var index = _.findIndex($scope.drugs, {_id: data._id});
//$scope.drugs.splice(index,1);
console.log($scope.drugs);
$rootScope.$emit('refreshDrug', index);
}, function(data){
}).finally(function(data){
$scope.refresh();
});
}
I didn't know why it didn't works with events. But if saveDrug in modal result but sumbit form - work fine.
Now code looks like
$scope.resolveDrug=function(index){
$scope.drug={};
var drugs = $scope.drugs;
$scope.drug=angular.copy($scope.drugs[index]);
var scope=$scope;
$modal.open({
templateUrl:'app/interactions/partials/modals/resolveDrug.html',
controller: 'DrugsListController',
scope: scope,
resolve: {
drug: function () {
return $scope.drug;
}
}
}).result.then(function(data){
}, function(data){
}).finally(function(data){
});
}
$scope.saveResolvedDrug = function(drug){
DrugsService.addResolvedDrug(drug).then(function(data){
var index = _.findIndex($scope.drugs, {_id: data.data._id});
if(data.data.ingredients && data.data.ingredients.length > 0){
data.data.ingredients = JSON.parse(data.data.ingredients);
}
$scope.drugs.splice(index,1);
return true;
});
return true;
};