AngularJS指令需要观察两个属性

Sea*_*ess 7 html javascript angularjs

我在Angular做一个游戏.每个玩家对象都有x一个y属性.每当玩家移动时,我想启动一个计时器,它在精灵表中循环几个背景位置.

我以为我会用指令做这件事.问题是指令通常只允许你设置一个表达式来监视:

// "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"/>
Run Code Online (Sandbox Code Playgroud)

关于这种方法的test好处是,指令不必假设范围具有任何特定属性.您告诉它在使用指令时要使用什么.

问题是,在我的情况下,如果x或y改变,我需要踢掉一些东西.我怎样才能做到这一点?

<div test="player.x, player.y"/>
<div test="player.x" test-two="player.y"/>
Run Code Online (Sandbox Code Playgroud)

有没有最好的方法来做到这一点你能想到的?基本上我想制定一个指令,如果任何一个属性发生变化,它会对定时器做一些事情.

Pet*_* BD 14

在我看来,最简单和最易读的解决方案是使用两个属性并简单地设置两个手表:

// "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" />
Run Code Online (Sandbox Code Playgroud)

  • 现在有`watchGroup`你可以将手表压在一起`范围.$ watch([attrs.test,attrs.testTwo],doStuff);` (2认同)

max*_*sam 7

我会尝试在$ watch函数中使用一个函数.

这是掠夺者

var app = angular.module('plunker', [])
.directive('myDir',function(){
  return {
    restrict:'E',
    template:'<span>X:{{x}}, Y:{{y}}</span>',
    link:function(scope, elm, attrs){
      scope.$watch(function (){
        var location = {};
        location.x = attrs.x;
        location.y = attrs.y;
        return location;
      }, function (newVal,oldVal,scope){
        console.log('change !');
        scope.x = newVal.x;
        scope.y = newVal.y;
      }, true);
    }
  };
});

app.controller('MainCtrl', function($scope) {

});





 <div>X: <input type='text' ng-model='x'/></div>
  <div>Y: <input type='text' ng-model='y'/></div>
  <my-dir x='{{x}}' y='{{y}}'></my-dir>
Run Code Online (Sandbox Code Playgroud)