KenSchnetz KenSchnetz - 21 days ago 6
HTML Question

AngularJS Conditional ngStyle not applying

I am trying to make my input width respond to an AngularJS scope variable, by setting it's width conditionally with ng-style. I have gotten this to work beautifully with text-align, but for some reason it is not working with width...

The 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>


The JS:

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


Check out the JSFiddle **THIS HAS BEEN UPDATED TO REFLECT KUKKUZ'S SOLUTION, WHICH WORKS

EDIT:
This is different from the suggested possible duplicate because I am not trying to apply a static CSS class, I am trying to use a variable to conditionally apply a style inline.

Answer

I see you are using Angular 1.0.1. You can use this:

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

See demo below:

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>