0

I know we should not do DOM manipulation in controllers , I have googled the answer and tried to understand it , what I got is directives are used for their reusability , but I am getting confused is the same goes for controller , we can use a controller and them can have any element inside it. And can use it's functionalities or event handling using it. So why not controller??? Am I missing some point, or my understanding is wrong regarding controllers and Directives ???

YepMe
  • 159
  • 2
  • 11
  • 2
    Possible duplicate of [Separating DOM manipulation from Angular controllers - Best Practice wanted](https://stackoverflow.com/questions/28988547/separating-dom-manipulation-from-angular-controllers-best-practice-wanted) – DGarvanski May 31 '17 at 10:27
  • Actually I ave gone through that answer before but it is still not clear – YepMe May 31 '17 at 10:58
  • The answer would be the same, however. Controllers should handle the view model, services handle the business logic, directives are for DOM manipulation. It's not mandatory that you do it that way, but it is a better structure, which leads to cleaner, better, more logical and understandable code. It's not that controllers **can't** handle DOM manipulation it's that they **shouldn't** – DGarvanski Jun 01 '17 at 07:27

1 Answers1

0

Controller in angular are for handling models. For logic we create services , for dom manipulation they provide directive and for view rendering changes filter are available .Therefore, every component in angular have its own role .

Now, we use directive for dom manipulation as it provide dom jqlite object of element on which we can use angularjs jqlite method

https://docs.angularjs.org/api/ng/function/angular.element

It also makes our code reusable . Other feature of directive like compile(pre,post) , isolated scope , require , template binding gives you easy control on dom . To achieve these things in JavaScript we need to write lots of code .

vaibhavmaster
  • 659
  • 6
  • 10