[英]AngularJS directive needs to watch two properties
我在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"/>
關於這種方法的好處是, test
指令不必假設范圍具有任何特定屬性。 您告訴它在使用指令時要使用什么。
問題是,在我的情況下,如果x或y改變,我需要踢掉一些東西。 我怎樣才能做到這一點?
<div test="player.x, player.y"/>
<div test="player.x" test-two="player.y"/>
有沒有最好的方法來做到這一點你能想到的? 基本上我想制定一個指令,如果有幾個屬性發生變化,它會對定時器做一些事情。
在我看來,最簡單和最易讀的解決方案是使用兩個屬性並簡單地設置兩個手表:
// "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" />
我會嘗試在$ 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.