Share scope between Angular Bootstrap Modal and parent Controller - javascript

I want to show a modal in one of my controllers, and have that modal share the same scope as that controller so that it can modify data of that original scope. I tried doing something like this:
$scope.modalInstance=$modal.open({
templateUrl: 'some_template.tmpl.html',
scope:$scope
});
But when I bind to properties of that scope from within the modal, they don't change. It can read them though. I don't want to use a result promise.

If you don't want to resolve data (which you should be doing), you can create a service which holds your data and $inject it in both your parent controller and the modal controller.

Related

AngularJS: function is not a function

I have an AngularJS app, and on one of the pages, I have a number of widgets, each one displaying some information about the status of a part of the system.
I am currently working on adding the functionality to allow the user to 'hide' the heading of a given widget.
There is a 'Settings' button on the page where the widgets are displayed, which, when clicked, overlays a toolbar on top of each of the widgets. The toolbar has a number of buttons- one of which is another 'Settings' button, which opens up a dialog that allows the user to change the settings for that particular widget.
I have added a checkbox to the dialog, to enable the user to 'hide' the heading for that particular widget from view:
When the checkbox is selected on the dialog, and the user clicks 'Preview', I am expecting (eventually- I'm still working on the implementation of the feature) the heading for that particular widget to be hidden. However, currently, when the user clicks 'Preview', whether the checkbox is selected or not, I am getting an error in the console that says:
TypeError: $scope.widget.toggleWidgetHeading is not a function
This error is coming from the $scope.preview function in ctrl.js called when the 'Preview' button is clicked on the dialog:
}).controller('WidgetPickerCtrl', function($scope, $timeout, fxTag, gPresets, appWidget) {
...
$scope.preview = function(e) {
$scope.widget.toggleWidgetHeading();
...
};
...
});
I don't understand why I'm getting this console error, since toggleWidgetHeading() clearly is a function...
If I right-click on the function call above in Sublime, and select 'Go to definition', I am taken to the directive.js file where the function is defined:
.directive('appWidget', function($timeout, fxTag, appColorFilter) {
return {
...
link: function($scope, $element){
...
var toggleWidgetHeading = function(){
...
}
...
}
}
})
Also, clicking the 'Preview' button on the dialog no longer closes the dialog...
Why is it that I'm being told that this function call is not a function when it is clearly defined as one? Is the issue here something to do with the scope (i.e. the fact that I'm calling the function from ctrl.js, even though it's defined in directive.js)?
The definition of your directive, where you added ..., is actually a really relevant part about directives scopes.
Directives can implement several kind of scopes. You can actually inherit and access the parent scope, or you can have an isolated scope for example.
You may read about that in the official documentation where is well explained:
https://docs.angularjs.org/guide/directive
However, whatever will be the scope you use, by default AngularJS implements the inheritance of scopes, as usually inheritance works: children can access parent methods, but parent cannot access children's methods.
Here it seems that from the parent scope (the controller) you are trying to access the directive's scope, which is actually no possible. (even if in the link function you define the toggleWidgetHeading as private variable, and not associated to the $scope itself - but it won't work either).
So you have few options in these cases:
Define your "visible properties" inside a service and inject the service inside the directive and the controller. Then use the service in order to access and change these values, so that they will be sync between the controller and the directive
Add a scope parameter to the directive as callback & and provide a function from the controller which returns the chosen visibility of the widget, so from the directive you can call that function and get back the value of widget's visibility
Add a scope parameter as two way data binding = in the directive, which is bound to the widget's visibility of the controller, so that you have that always sync between your controller and your directive
Use events in order to communicate between the controller and the directive, broadcasting an event from the controller when the visibility changes, and reading the event from the directive getting the widget's visibility value
I hope it makes sense

modalService cannot talk with controller and view

The code at this plnkr has a modal which pops up when a user clicks on a "Click to take quiz" button which calls a controller method that in turn calls a modal service. To get the plnkr to work, click anywhere in the code and press the space bar to add white space in a way that does not effect syntax. This will trigger plnkr to re-initialize the app and make the modal pop up after you click the button.
The problem is that the text printed in the modal does not update dynamically when timeLeft variable counts down. And also, the user's button click does not update the quizAnswer variable. In short, the modal is not able to talk interactively with the calling controller and view.
What specific changes need to be made to the plnkr to get the modal text to show the dynamic countdown, and to get the modal buttons to change the value of the $scope.quizAnswer variable?
Also, I have been carefully reading the documentation at this link. I think that the answer may be related to:
1.) $uibModal's options parameter passed in open(options) contains the parameter scope that defines the parent scope to be used for the modal's content, and also property bindToController which, when set to true, binds the scope property to a specific controller defined by controllerAs.
2.) The open(options) method returns a modal instance, which includes close(result) and dismiss(reason).
I suspect that the solution lies in these methods and parameters, but I am looking for good examples and would appreciate some experienced eyes looking at this problem.
NOTE: The solution to this came in the comments below the accepted answer, especially the link to another posting that contains 2 lines of code for emitting the modal button click's results back to the parent controller.
You have a number of issues.
First, takeQuiz at navigation.js - line 16, should be attached to $scope, not this, since this will mutate depending on context.
Second, $scope.$apply and $scope.$digst(); at navigation.js - lines 29/30 are unnecessary since you will already be in a digest cycle. They should be removed else they'll trigger an error.
Finally (and this is the meat of your issue), you are misunderstanding how modal options are bound across when creating a modal instance. It is NOT two-way binding; it is a single extends from one object to another. As a result, trying to bind to the options (or creating a concatenated string with the timeRemaining) will not update once it's bound across.
Instead, one possibility is to create an event handler inside of the modal and broadcast on each tick, updating the modal. In addition, if you pass the body text as prepend and append text, it is easier to insert your timestamp value:
You will need to inject (and broadcast from) $rootScope in your navigationController, since the modalService is registered somewhere very high in the scope chain.
On each tick, broadcast the time remaining navigation.js:
$rootScope.$broadcast('timeRemainingTick', $scope.timeRemaining);
In your modalService.js, register to receive the event inside of the controller assignment:
var timeRemainingUnbind = $scope.$on('timeRemainingTick', function(event, newTick) {
$scope.modalOptions.timeRemaining = newTick;
});
Finally, make sure that you unbind the event by calling timeRemainingUnbind() in the close events of your modal to prevent memory leaks:
$scope.modalOptions.ok = function (result) {
timeRemainingUnbind();
$modalInstance.close(result);
};
$scope.modalOptions.close = function (result) {
timeRemainingUnbind();
$modalInstance.dismiss('cancel');
};
See my working forked plunker here

How can I call/trigger one controller function in other controller in Angular js [duplicate]

This question already has answers here:
Can one AngularJS controller call another?
(14 answers)
Closed 7 years ago.
<div ng-app="myApp">
<div ng-controller="FirstController">
//In this controller i am having one insert Functionality on ng-click
</div>
<div ng-controller="secondController">
//In this controller i am having one insert Functionality on ng-click
</div>
<div ng-controller="FinalController">
//Here on ng-click i want to trigger all the other controller's click events
</div>
</div>
Actually i am building an angular js app where i have different section's the the user can save his entered data, so for that reason each controller here is behaving as single entity and performing crude operations on button click of each controller.
Now as in each controller there is insert functionality implemented on ng-click to send the data to the table. in final controller there is a save button where we need to trigger all the insert click's of different controllers how can i achieve this any quick suggestion's are appreciated.
You can use $rootScope for that. Inject $rootScope into all controllers add then emit an event from finalcontroller to other controllers like this
In final controller
$rootScope.$emit('triggerClick'); // when you want to trigger click in other controllers
In firstController and secondController
$scope.yourFunction = function(){ //This will be executed on ng-click
// InsertFunction code
}
$rootScope.$on('triggerClick', function() { // this will be executed when you trigger from finalController
// InsertFunction code
})
you'll need to broadcast a message from your final controller, and act upon it in the other controllers.
FinalController
function trigger(){
$rootScope.$broadcast('yourEventName');
}
FirstController
$rootScope.$on('yourEventName', function(){
//do your insert functionality
})
If you want to trigger other controllers actions you must use services.
Implement your trigger actions in a service and then inject it in the other controller.
This is the "best practice" way to do that.
You should use events to communicate between modules / in this case controllers in your angularjs apps. That is the proper approach.
ie using $on, $broadcast and $emit.
Emmiter
function someFunction(){// your buttonclick or whatever you want to sstart communication with
$rootScope.$broadcast('eventName',{data: 100});//this should be remembered
}
Receiver
$rootScope.$on('eventName', function(event,args){// and here is why
// acces with args.data
})
Look at this post , the answers apart from the correct one are also a good dive into the approaches for communication b/w app components.

assign custom unique id's to angular directive instances?

I wrote a sliding panel directive and I can't figure out how to have multiple instances of the directive on a page. I am passing in a panel-id attribute to the directive and I need to figure out how to use that id to trigger the correct panel instance. I have a codepen here:
http://codepen.io/mcastre/pen/Ejzebd
Thanks!
What you can do is have the individual directives register themselves with the panelService on link (add a method called registerPanel(scope) to the service for example).
Then your controller methods like toggleWeightPanel() just need to pass in the id that identifies your panel and it can search through the scopes of all registered panels to find the matching one, and call the appropriate method on it.
Somewhere in your controller scope you should keep a list of panel ids that you can use in your ng-click directives and pass down into your panel directives.
Does that make sense?
You really shouldn't need a service for this. A simple true/false param in your code and an ng-show="ShowMe". And in your code set $scope.ShowMe = true;

What is the proper way to extend the behavior of a custom Angular directive?

I've written my own Angular directive called <my-table> since I use it multiple times, passing in different data to display. All of the tables have a button that when clicked, a popup form appears, like so:
However, for one of the <my-table> directives, I want to extend the behavior so that it acts slightly different from the other <my-table>s. For example, let's say that for the form that pops up, an alert box will appear when you click Submit, displaying data present in that <my-table>'s scope.
My question is, what is the best way extend the behavior of a given directive while still being able to access the directive's scope? Is this possible, or am I simply using directives incorrectly?
You can do something to this extent:
<my-table on-submit="doSomething(message)"></my-table>
In your my-table directive definition you would bind your callback to the scope:
scope: {
'submit': '&onSubmit'
},
Then in your controller you define your function:
$scope.doSomething = function(message) {
alert(message);
}
In your template, where you define the submit button, you would do:
<button ng-click="submit({message: 'bye!'})"></button>
You can reference angular's documentation for more info:
https://docs.angularjs.org/guide/directive

Categories

Resources