AngularJS Conditional ngStyle没有应用

时间:2016-11-17 01:34:48

标签: javascript html angularjs conditional directive

我试图让我的输入宽度响应AngularJS范围变量,通过ng-style有条件地设置它的宽度。我已经使用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类,我试图使用变量来有条件地应用内联样式。

2 个答案:

答案 0 :(得分:1)

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

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

见下面的演示:

&#13;
&#13;
var vfApp = angular.module('vfApp', []);
vfApp.directive('resize', function($window) {
  return function($scope) {
    $scope.doResize = true;
  };
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

doResize ? '100%' : '10%'.
您的js文件中的

doResize为false。如果你不理解三元表达式,那么它们就是浓缩的。代码的未压缩形式是:

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

所以你有两种方法可以解决它:

  1. $scope.doResize = false;更改为$scope.doResize = true;
  2. ternary expression更改为doResize ? '10%' : '100%';
  3. 希望有所帮助。