How to disable Spotlight indexing when on battery?
jherran's answer helps you with disabling Spotlight indexing, but does not address the part of the question about toggling automatically when AC power is connected or disconnected.

You could use sudo mdutil -i off / and sudo mdutil -i on / in conjunction with a listener for when AC power is disconnected. Using something like ControlPlane will satisfy your requirement for automatic toggling. It supports "Current power source" as an event to listen for. It is free and open source.

You might be against using a third party solution. To roll your own, try writing a script that loops checking pmset -g ps | grep -c 'AC Power' with a sleep interval in between. If AC is connected, it outputs 1 (0 otherwise).