为什么可以't我在Angular.js中为transform:translate创建了一个字符串

Why can't I create a string for transform:translate in Angular.js?

本文关键字:创建 translate 字符串 一个 transform 中为 js Angular 我在 为什么      更新时间:2023-09-26

我正在尝试这个

$scope.graph.transform = "transform: translate(" + 
                          $scope.graph.width + "," + 
                          $scope.graph.height + ");";

我从得到的一切

<h3>transform: <span ng-bind="graph.transform"/></h3>

这是吗

transform: transform: translate(undefined,undefined);

但我知道价值是存在的,因为如果我做这个

<h3>transform: <span ng-bind="graph.height"/></h3>

我得到

transform: 336

编辑:

这也是代码的一部分:

     $scope.graph = {};
     $scope.$watch(function(){
         return $window.innerWidth;
     }, function(value) {
         $scope.graph.width = value * 0.5;
     });
     $scope.$watch(function(){
         return $window.innerHeight;
     }, function(value) {
         $scope.graph.height = value * 0.5;
     });

因为这个:

$scope.graph = {};

你可以默认使用

$scope.graph = {
    height: 0,
    width: 0
};

高度和宽度是未定义的,直到手表触发。你做手表的方式不是检查是否有未定义的。手表的第一个触发器是未定义的,在您调整屏幕大小之前,它可能不会再次触发。

$scope.$watch(function(){ 
    return $window.innerWidth; 
}, function(value) {
    if(value){
        console.log(value);
    }
});
$scope.$watch(function(){ 
    return $window.innerHeight; 
}, function(value) {
    if(value){
        console.log(value);
    }
});

此外,调整窗口大小时不会触发$digest循环,只有用户事件,因此您需要执行以下操作:

$window.addEventListener('resize', debounce(function(){
    $scope.$apply();
}, 500));

你会想取消对事件的反弹,这样它就不会每毫秒被调用一次,它会使你的应用程序崩溃,这只是使用David Walsh的取消反弹函数,但许多库(比如lodash,也许是jquery)已经在中内置了一个

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

同样,以你现在的方式绑定值不会用$watches更新。你可以做:

<h3>transform: translate({{ graph.width }}, {{ graph.height }});</h3>

这是更新后的plunkr,你必须调整右侧窗口的大小才能触发$watch。

如果你想做一个$watchGroup,你可以传入一个函数数组,而不仅仅是一个函数

$scope.$watchGroup([function(){
    return $window.innerWidth;
}, function(){
    return $window.innerHeight;
}], function() {
    $scope.graph.width = $window.innerWidth / 2;
    $scope.graph.height = $window.innerHeight / 2;
});

这是一个演示

的plunker