Here is the problem :
I try to do things like this :
Click on a directive triggers an event
Event sends data to a rootScope function which sets a scope variable value with new data
Another directive has a ng-model in its template which is supposed to reflect the previously changed var
Data should be updated in the view AND model. Model is ok (update done), but view update does not seem to trigger automatically, it only updates when I click on the "show button" (see fiddle)
Here is the corresponding jsfiddle I made, with comments :
http://jsfiddle.net/wkmm576m/7/
Here is the code which I think is making trouble... :
app.directive('addEditInput', function() {
return {
restrict : 'E',
template : '<div id="editForm"><input type="text" ng-model="currentVar.name" /><br/></div>'
}
});
In fact, I return a template, with ng-model. But the ng-model is not updated when its value changes from anywhere else...
Tbh, I'm a bit confused with directives and scopes communications - data....
Thanks for reading / help
Short answer - you need to call $scope.$apply in top controller:
http://plnkr.co/edit/QEjzlsJj4fh1eeqBXSvt?p=preview
Long answer: you bind usual js function to usual js event, so when user clicks on element - your function executes. Thats all. When you use ng-click - it will trigger digest cycle and your bindings will be updated. So you need to trigger it manually, so you call $scope.$apply.
Note: better do not use jquery where you do not need to. I.e. use $element.bind('click',function(){ instead of $().on...
Related
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
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
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
I am new to AngularJS and trying to set up a function that gets called upon whenever a variable is changed.
Currently I have a dropdown-menu, with ng-model bound to a $scope.userRating. And I am trying to get a function that gets called immediately when the user changes the value using the dropdown.
I have been looking at $watch, but not quite sure on how to get it to work. I also tried to make a ng-click function on the in the html, but ng-clicks don't seem to trigger.
You should use $watch .
Example-
$scope.$watch('modalVarible',function(newVal,oldVal){
//do your code
}
Here on the change of variable 'modalVarible' this watch will be called.
we can use $watchGroup in controller of our directive to bind $scope variable changes (bidirectional)
$scope.$watchGroup(['var1','var2'],function () {
});
you can also check this question.
I modified the AngularUI-Bootstrap direvtive for tooltips to help me display error messages, here is what I did so far: http://jsfiddle.net/distractedBySquirrels/TaAHZ/
But I have a problem with the dynamic messages. The first time you mouseover the first input field, the message is in the wrong place, this is because the model is not correctly updated yet. Of course, after the second mouseover the tooltip is in the right place. But if the message to display changes again the same failure occurs.
I am using $parse to update the template:
$parse('tt_content').assign( scope,
getErrorMessage( ctrl.$error ) || attrs.tooltip
);
Seems like not all the listeners have revceived and updated and "ttHeight" and "ttWidth" are still set to the "old" values. The correct update of the message/model only works with the $observe, which is illustrated by the third example.
I am stuck and don't know what I did wrong? :(
The problem is that when you modify your models with $apply, you need to manually activate the digest cycle in order to notify all watchers of such models. So basically, you need to add scope.$digest(); whenever you change the scope doing things like scope.$apply( show );
I modified your code with my suggestions here http://jsfiddle.net/TaAHZ/2/