arg20
arg20

Reputation: 4991

How do I port this from jQuery to AngularJS

I'm working on an Artificial Intelligence project. I have in a webpage a little tank and a grid, the tank is merely a div like this:

<div id="agent" ></div>

Then I use jQuery to do something like this:

agent = $('#agent').setUpAgent();

//examples of usage:
agent.goUp();
agent.goLeft();
agent.doActions['left','right','down']; // (will execute: goLeft, goRight, goDown functions.

The implementation of these methods is fairly simple:

Agent.prototype.goLeft = function() {
    this.agentDiv.rotate(45); // rotate the jQuery-wrapped div
    this.agentDiv.animate({"margin-left": "-=51px"}, "slow"); //51 is the step size
}

As you can see the movement on the agent is achieved by changing its margins through jQueryAnimate. Is it logical to port this to angularJS?. For instance like this:

<div agent="nameOfJavascriptObject" ></div>

since AngularJS will update my view automatically by setting up watches, how should I approach this? Should I have a model object with "actionsToBeExecuted" and when it's not empty I trigger the "goUp(), goLeft()..." etc functions? How can I make it so that functions are triggered when it changes? I am clueless as to how to port this, or even whether it should be ported at all.

Upvotes: 1

Views: 764

Answers (1)

Tosh
Tosh

Reputation: 36030

Here is the simple example, how you could do it:

http://plnkr.co/edit/7wG08Twvt7jufIpvjHFl?p=preview

You can simply express the appearance property of the agent (such as position, angle) using javascript object and manipulate the properties.

In the directive, bind that object into scope and $watch the apperance property and animate based on how the properties changes. (e.g. if angle changes then call rotate())

Upvotes: 4

Related Questions