Angular Bootstrap Modal binding issue - javascript

I'm working with Angular Bootstrap and actually I'm trying to update correctly my model using a Modal.
Here is the very simple code:
controller:
function open(room) {
var roomModal = $uibModal.open({
templateUrl: 'room-modal.html',
controller: 'RoomModalController',
controllerAs: 'modal',
resolve: {
room: room
}
});
roomModal.result.then(function (response) {
RoomsService.update({
roomId: response._id
}, response).$promise (etc...);
});
}
Modal Controller:
var vm = this;
vm.room = room;
vm.save = function () {
$uibModalInstance.close(vm.room);
};
vm.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
Basically I'm resolving the Room to get a few information about it and then if needed I wish to update a few information about the room within the modal.
It is working fine unless I do not want to update some information and I click "close".
What happen is: if I updated a few information and then I click "close" the information has not been updated on the database (OK) but has been updated in the main view... Because Angular bind the Modal information to the main view...
It is quite weird because I'm passing those information to a separate scope (vm) and unless I do not click save I should not expect this behavior...
What I'm doing wrong here?!?

In your RoomModalController deep copy the room object to prevent when updating that the model is also updated.
vm.room = angular.copy(room);
Now this object will take care of the modal binding, and will not interfere when changed to your root scope vm.room object.
To finalize saving this data, you have to save the vm.root modal object to your database, and also update the root scope vm.room object according these changes made in the modal.

Related

Best way to toggle Booleans between $rootScope and and a controller

I have a navbar directive which sits above ng-view. It utilises the $rootScope to trigger events to show buttons in certain views.
I am trying to add a button to the directive template which will switch a boolean in a controller for a particular view. The view shows a period of time and each period has a particular boolean that I want to switch from the directive.
The boolean value is saved in a local storage object which is initialized when each iteration of this particular view is loaded.
First, the value needs to be communicated to the directive so the button can display as being set to true or false. When the switch is toggled, the value of that boolean needs to make its way from the directive, through the $rootScope, to the controller and then be saved in the storage object.
When the view is changed, the whole process needs to repeat. The switch needs to be able to be switched on and off multiple times, obviously.
At present, I am emitting the value from the controller to the $rootScope and then listening for that value in the directive link function.
However, what is the best way to get that $rootScope value BACK into the controller. I tried setting up a $rootScope.$watch in the controller which appeared to work on any single page but when navigating between different time periods, the $rootScope value of the boolean was not resetting properly.
I tried resetting the value in the controller initialization as follows:
$rootScope.booleanValue = false;
but this didn't work.
I have also tried the following:
$scope.$on('$routeChangeSuccess', function (next, current) {
$rootScope.booleanValue = false;
});
but I can't get the whole cycle to work properly. It still seems as though the value of the property in the $rootScope is not resetting from the view before and is then carrying over when an adjacent pay period view is loaded.
I hope this makes sense. I will save you from too much code as I think the basic idea is here.
What you are trying to do is share state from your navbar directive (an isolate scope) and your view's controller. I recommend you use a factory provider service to share that state:
angular.module('myApp').factory('navbarState', function (){
return {started: false}
});
In your navbar directive, inject the service and store the state in that service:
angular.module('myApp').directive('navigationBar', [
'$rootScope',
'navbarState',
//'NavigationStackService',
//'NavigationBarService',
function ($rootScope, navbarState) {
function link(scope, element) {
scope.startEditMode = function(){
console.log("Edit clicked");
navbarState.started=true;
//NavigationBarService.hideNavigationEdit();
//NavigationBarService.showNavigationDone();
};
scope.finishEditMode = function(){
console.log("Done clicked");
navbarState.started=false;
//NavigationBarService.hideNavigationDone();
//NavigationBarService.showNavigationEdit();
};
}
return {
templateUrl: 'templates/navigation-bar.html',
restrict: 'E',
scope: {},
link: link
};
}
]);
In your view controller, retrieve the service, put it on the controller's scope, and use it in your template.
angular.module('myApp').controller('controller2', function(navbarState) {
console.log("view controller2 started");
var vm = this;
vm.navState = navbarState;
vm.message = "hello from ct2";
});
The DEMO on JSFiddle.

Angular: how to make a "search" take you to another route and display results?

I have a main page with a nav, and each nav option takes you to another route. It all looks like a single page app, but each "page" has it's own route and controller.
My problem is that I want to put a search box in the navbar. When someone uses the searchbox, I want to take the user to the "search" route and then display the results. I'm having a lot of trouble figuring out these two issues:
Where do I store this "searchbox" logic? E.g. when someone searches, they choose the type of search from a dropdown, then the search query in the inputbox. I have special logic to automatically choose which dropdown value based on the value typed in the inputbox.
How do I redirect to the
"search" route and display the results based on the input from the
previous page?
It's probably clear I'm a newby to Angular. I'm happy to work out the details, but I'm mainly looking to understand how to structure the solution to this problem. Thanks in advance for your help.
What I love about Angular the most is the amount of options you can apply.
Your goal can be reached either by using a service. A service is a singleton class which you can request from controllers. Being a singleton what ever value you store in the service is available to all controllers. You can than either $watch for value change, use $broadcast to notify data change or use $routeParams to send data with route change.
A service is built as follows :
The following assume you have a global module var named 'app'
app.service('myService', function(){
var myValue;
this.getMyValue = function(){
return myValue;
};
this.setMyValue = function(value){
myValue = value;
};
});
Then you request a service from a controller like you request an angular service such as $scope.
app.controller('myController', ['$scope', 'myServce', function($scope, myService){
$scope.myValue = myService.getMyValue();
//Example watch
$scope.$watch('myValue',function(){
//Search criteria changed!!
}, true);
}]);
Angular is terrific..have fun coding
Basically you would want an own state for your search page, so this is where we begin (I expect you to use the ui-router and not Angulars built in router):
.state('search', {
url: "/search",
templateUrl: "pages/search.html",
controller: 'SearchController as ctrl',
params: { searchString: {} }
})
As you can see, I've defined an additional parameter for the search string that is not part of the URL. Of course, if you like, you could change that and move the parameter to the URL instead:
.state('search', {
url: "/search/:searchString",
templateUrl: "pages/search.html",
controller: 'SearchController as ctrl'
})
The actual search input is pretty straight forward as well, because it's only HTML:
<input type="text" ng-model="searchString" on-key-enter="ctrl.goSearch(searchString)">
The function for the state change has to be placed in the controller for the primary template (e.g. the controller of your navigation bar if the search is located there):
var vm = this;
vm.goSearch = goSearch;
function goSearch(searchString) {
$state.go('main.search', { searchString: searchString });
}
Of interest is also the on-key-enter directive that I've added:
angular.module('your.module')
.directive('onKeyEnter', OnKeyEnter);
function OnKeyEnter() {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.onKeyEnter);
});
event.preventDefault();
}
});
};
}
On pressing the enter-key, it will call the function you supply as attribute value. Of course you could also use a button with ng-click instead of this directive, but I think it simply looks better.
Last, but not least, you need a Search Controller and a HTML template for your search page, which I won't give to you, as it is up to you what you display here. For the controller, you only need to know how you can access the search string:
angular.module('your.module')
.controller('SearchController', SearchController);
SearchController.$inject = ['$scope', '$stateParams'];
function SearchController($scope, $stateParams) {
$scope.searchString = $stateParams.searchString;
/* DO THE SEARCH LOGIC, e.g. database lookup */
}
Hope this helps to find the proper way. :)

AngularJS view not updating when $scope.$apply is called

Here's the workflow:
A user's account page should list all of the object owned by that user.
Next to each object is a "delete" button that opens a Bootstrap modal. The modal asks the user if they truly want to delete the object, and if they confirm, then the modal should dismiss, the object should be deleted, and the view should update to reflect the deletion.
I am dismissing the modal using the data-dismiss attribute on the confirmation button inside of the modal.
Here is the function in my controller that deletes the object and (should) update the view:
$scope.deleteObject = function(object) {
object.destroy({
success: function(object) {
$scope.$apply();
},
error: function(object, error) {
// handle error
}
});
};
However, I have to refresh the page to see the updated view with the object removed.
Is there another way I should be using $scope.$apply?
EDIT: I found a workaround by creating a new $scope level function to load my collection of objects. Previously, this was done when the controller is loaded (not attached to any particular function.
In other words, my old code did this:
.controller('AccountCtrl', function($scope) {
var query = new Query('Object');
query.find().then(function(objects) {
$scope.objects = objects;
});
$scope.deleteObject = function(object) {
object.destroy({
success: function(object) {
// do something
}
});
}
});
Now I've wrapped the find code in a $scope level function, which I can call explicitly when an object is destroyed:
.controller('AccountCtrl', function($scope) {
$scope.getObjects = function() {
var query = new Query('Object');
query.find().then(function(objects) {
$scope.objects = objects;
});
}
$scope.getObjects(); // call when the view loads
$scope.deleteObject = function(object) {
object.destroy({
success: function(object) {
$scope.getObjects(); // call again when an object is deleted
}
});
}
});
I'm still hoping there is a cleaner solution to this, i.e. one where I don't have to manually update by object collection.
In your success you have to modify the local $scope.objects.
In you last exemple you should try this (code not tested, but this is how it should look):
$scope.deleteObject = function(object) {
object.destroy({
success: function(object) {
var objectIndex = $scope.objects.indexOf(object);
$scope.objects.splice(objectIndex,1);
}
});
}
In your controller you take the responsibility for updating your model. Angular take the responsibility for updating the view. Calling again the $scope.getObjects() is a way to do it. But the cleaner way is to implements your update of the model in case of success. You should also give an error method in case the server response is an error.
If you have correctly bind the collection to your view, i should update after a delete. Tell me if it helped you out.

Using AngularJS "copy()" to avoid reference issues

I'm displaying a list of items, each of which has an "edit"-button next to it. A click on that opens an angular ui modal window and the user can change some properties of the specific item.
Now, what bugged me was that when typing in this edit-window, the specific item in the list of items reflected the changes immediatly. I only wanted it to update when the user clicked 'ok' in the modal, and to not change at all if the user chose 'cancel'.
My workaround uses copy to make a, well, copy of the chosen item that then serves as model for the view:
var modalInstance = $modal.open({
templateUrl: 'scripts/app/views/editBond.html',
controller: function ($scope, $modalInstance, bond) {
$scope.bond = angular.copy(bond);
$scope.ok = function () {
$modalInstance.close($scope.bond);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
resolve: {
bond: function () {
return bond;
}
}
});
Is using angular.copy() appropriate to avoid such issues? Is this a scope issue at all?
Yep, using angular.copy() is absolutely appropriate here. If you want something more advanced you might want to checkout angular-history

How does passing data around different views/pages work on angularJS

I am learning angularJS, went through few tutorials and sort of know my why around. It seems that the page never refreshes, therefore a value created in one view should be available in another view, right? I am testing this in a shop scenario. If we are at the main view, and we click on "add to cart" that should trigger a function in the background and add the item in an array. Then when we go to the cart view, we can see the item listed there. But this does not work.
I have a cart controller:
angular.module('shoppingCartApp')
.controller('CartCtrl', function ($scope) {
$scope.cart = [
'one item'
];
$scope.pushing = function(item){
this.cart.push(item);
};
});
In the main view (which doesn't have access to this controller) I have.
<div ng-controller="CartCtrl">
add to chart
</div>
And on the cart view I display the cart object
<div ng-repeat="item in cart">
{{item}}
</div>
We only see the one item. I have also added the ng-click attribute to this page as well, just to test, and it does work, however, if we go home and come back, the item is gone.
From the idea that the page never reloads, should the pushed items stay in the array? here is the simple example in action
Thanks
Controllers are not singletons, so when you change the view the $scope gets destroyed and a new controller will be initialized. If you want persistent data across different views then you want to look at using a service to store it, since they are singletons.
If you create something like
angular.module('app')
.service('cartService', [function() {
var cart = [];
var add = function(item) {
cart.push(item);
};
var get = function() {
return cart;
};
return {
add: add,
get: get
};
}]);
Then you can add that as a dependency in your controllers and use that for backing your data rather than using the $scope.
angular.module('app')
.controller('Ctrl', ['cartService', function(cartService) {
$scope.cart = cartService.get();
$scope.pushing = function(item) {
cartService.add(item);
};
}]);

Categories

Resources