AngularJS 条件 ngStyle 不适用

AngularJS Conditional ngStyle not applying

我试图通过使用 ng-style 有条件地设置它的宽度来使我的输入宽度响应 AngularJS 范围变量。我已经让它与 text-align 一起完美地工作,但由于某种原因它不适用于宽度...

HTML:

<body ng-app="vfApp">
    <!--This works...  --> <input resize ng-style="{ 'width' : '100%' }" type="text"/>
    <!--This does not?!--> <input resize ng-style="{ 'width' : doResize ? '100%' : '10%' }" type="text"/>
</body>

JS:

var vfApp = angular.module('vfApp', []);
vfApp.directive('resize', function () {
    return function ($scope) {
        $scope.doResize = false;
    };
});

编辑: 这与建议的可能重复项不同,因为我没有尝试应用静态 CSS class,我正在尝试使用变量有条件地应用内联样式。

如果您的目标是 100% width 值,问题很简单 ternary expression

doResize ? '100%' : '10%'.

在你的js文件中doResize是错误的。如果你不理解三元表达式,它们是一个浓缩的 if。您的代码的未压缩形式是:

if(doResize) {
  return '100%';
} else {
  return '10%';
}

所以你有两个选择来修复它:

  1. $scope.doResize = false;更改为$scope.doResize = true;
  2. ternary expression 更改为 doResize ? '10%' : '100%';

希望对您有所帮助。

我看到您正在使用 Angular 1.0.1。你可以使用这个:

ng-style="doResize && {'width':'100%'} || {'width':'10%'}"

参见下面的演示:

var vfApp = angular.module('vfApp', []);
vfApp.directive('resize', function($window) {
  return function($scope) {
    $scope.doResize = true;
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>

<body ng-app="vfApp">
  <!--This works...-->
  <input resize ng-style="{ 'width' : '100%' }" type="text" />
  <!--This does not?!-->
  <input resize ng-style="doResize && {'width':'100%'} || {'width':'10%'}" type="text" />

  <br/>isMobile value: {{doResize}}

</body>