Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
80
rated 0 times [  83] [ 3]  / answers: 1 / hits: 27424  / 12 Years ago, sun, november 11, 2012, 12:00:00

I'm making a game in Angular. Each player object has an x and a y property. Whenever the player moves, I want to start a timer that cycles through a couple background positions in the sprite sheet.



I thought I would do this with a directive. The problem is that directives normally only let you set one expression to watch:



// test directive
module.directive(test, function() {
return function(scope, element, attrs) {
scope.$watch(attrs.test, function(value) {
// do something when it changes
})
}
})

// my template
<div test=name/>


The nice thing about this approach, is the test directive doesn't have to assume the scope has any particular property. You're telling it what to use when you use the directive.



The problem is that in my case I need to kick something off if either x OR y changes. How can I do this?



<div test=player.x, player.y/>
<div test=player.x test-two=player.y/>


Is there a best way to do this that you can think of? Basically I want to make a directive that does something on a timer if any of several properties change.


More From » html

 Answers
17

The easiest and most readable solution in my opinion is to use two attributes and simply set up two watches:



// test directive
module.directive(test, function() {
return function(scope, element, attrs) {
var doStuff = function() {
console.log(attrs.test);
console.log(attrs.testTwo);
}
scope.$watch(attrs.test, doStuff);
scope.$watch(attrs.testTwo, doStuff);

}
})

// my template
<div test test=player1.x test-two=player1.y />

[#82057] Friday, November 9, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
Sun, Dec 5, 21, 00:00, 3 Years ago
Mon, Jun 14, 21, 00:00, 3 Years ago
Mon, Jul 22, 19, 00:00, 5 Years ago
Mon, Jul 8, 19, 00:00, 5 Years ago
;