質問

I hava a simple question after reading the post below and working for some time now on angular js.

the post : no dom manipulation from angular js controllers

the concerned point (from the post) : Do not use controllers to
Manipulate DOM — Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has databinding for most cases and directives to encapsulate manual DOM manipulation.


the question : if I have a simple angular app and on a button click i am calling a function of my controller. In that function I want to do some simple business logic and depending on that business logic output i want to hide/show a button.

What is the best possible way to do it.

My current way of doing this is : PLUNKER EXAMPLE (does this way of doing stuff breaks the law in the angular js realm. is that against testing? please correct me)

役に立ちましたか?

解決

The Angular guidelines don't say "do not use controllers to manipulate the dom" in the sense that you should never have the dom change as the result of something in a controller - but rather that you should never in a controller directly modifiy the dom. Don't use document.getElementById, don't use $("#element"), etc - never talk TO the dom, let your model take care of that by binding the model to the dom.

When you find yourself in a situation that you want to use jQuery to talk to the dom directly in a controller then it's time to look at directives. http://docs.angularjs.org/guide/directive

And I agree with @tasseKATT, move the ng-click code on the reset button code into a function - even if just for sanity.

edit

Is this testable? Yes - much more so than putting things inline in HTML or relying on/modifying the DOM directly.

In this situation all you have to test is that your scope functions do what they are supposed to - and trust that the Angular folks have already tested the fact that their bindings work as documented. You don't have to test that ng-click calls your function, you have to test that when called with whatever parameters your function does what your spec says it should.

As far as it being easier to write this type of code inline or in document.ready, etc - that's just a part of getting used to the Angular way of doing things. Coming from years of doing bindings with jQuery it definitely takes some getting used to. I'd argue that it's harder to do it the 'old' way.

Checkout the posts on this site that deal with testing Angular - there are write-ups on testing controllers, directives, services, etc - really helped putting it all together for me. http://www.benlesh.com/2013/05/angularjs-unit-testing-controllers.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top