Angular communication between controllers and directives

前端 未结 3 1879
再見小時候
再見小時候 2021-01-21 05:29

I have this piece of code which allows a user to leave comments on a list of items. I created a directive and listen to keydown in order to let the user submit a comment if

3条回答
  •  渐次进展
    2021-01-21 06:04

    What is the best way to communicate between controllers and directives?

    It depends... I like to first determine which type of scope is appropriate for a directive: no new scope, new scope, or new isolate scope. See When writing a directive in AngularJS, how do I decide if I need no new scope, a new child scope, or a new isolated scope?

    Once that has been decided, the next decision is to determine if the communication should really be going to a service. If so, the controller and directive would both inject the service and interact with it, rather than each other.

    If a service is not required, attributes are used to facilitate the communication between the controller and the directive. How that is done is determined by the type of scope the directive creates. Tip: if an isolate scope is not used, use $parse to get and set properties inside the directive, or to call methods on the controller from inside the directive -- see

    • How to set angular controller object property value from directive in child scope
    • https://stackoverflow.com/a/12932075/215945 - an example of calling a controller function with arguments

提交回复
热议问题