What is the easiest way to pass an AngularJS scope variable from directive to controller? All of the examples that I've seen seem so complex, isn't there a way I can access a controller from a directive, and set one of it's scope variables?
相关问题
- angularJS: ui-router equivalent to $location.searc
- Separate AngularJS Controllers Into Separate Files
- Angular ngAnimate not working first time on page l
- Ionic Spinner not showing up
- Upload file to Google Cloud Storage using AngularJ
相关文章
- Passing variable through URL with angular js
- Watch entire object (deep watch) with AngularJS
- Angular ng-if change span text
- Can ng-show directive be used with a delay
- AngularJS $routeParams vs $stateParams
- Multiple parameters in AngularJS $resource GET
- How to set class/style of accordion heading in Ang
- PUT to S3 with presigned url gives 403 error
Wait until angular has evaluated the variable
I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with
"="
in the scope. Here's three solutions depending on your situation.Solution #1
I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.
If your variable is changing, or is fetched through a request, you should use
$observe
or$watch
:And here's the html (remember the brackets!):
Note that you should not set the variable to
"="
in the scope, if you are using the$observe
function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 orscope.$watch(attrs.yourDirective, fn)
(, or #3 if your variable is not changing).Solution #2
If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use
$timeout
to wait until the$apply
has run. Also we need to use$emit
to send it to the parent scope app controller (due to the isolated scope in the directive):And here's the html (no brackets!):
Solution #3
If your variable is not changing and you need to evaluate it in your directive, you can use the
$eval
function:And here's the html (remember the brackets!):
Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519
Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED
For the interested: here's an article on the angular life cycle
Edited on 2014/8/25: Here was where I forked it.
Thanks @anvarik.
Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @