0

I'm new to angular js and I have some things need to be clear about angular js. Here is my sample code

<body ng-app="radioExample">
   <script>
   angular.module('radioExample', [])
     .controller('ExampleController', ['$scope', function($scope) {
       $scope.color = 'blue';
       $scope.disabled = false;

       if($scope.color == 'red'){
         $scope.disabled = true;
       }

     }]);
 </script>
 <form name="myForm" ng-controller="ExampleController">
   <input type="radio" ng-model="color" value="red" >  Red <br/>
   <input type="radio" ng-model="color" value="green"> Green <br/>
   <input type="radio" ng-model="color" value="blue"> Blue <br/>
   <tt>color = {{color | json}}</tt><br/>
   <tt>{{disabled}}</tt><br/>
  </form>

</body>

when I select the "Red" button, doesn't it update the value of $scope.disabled into true as I mentioned in if statement? when I need to do it, how can I achieve it?

thank you.

2 Answers 2

1

Solution 1

Simple solution would be to Define disabled as function so that angular recomputes in each digest cycle.

$scope.disabled = function() { return $scope.color === 'red'; }

Later use

<tt>{{disabled()}}</tt>

Solution 2

If you don't want disabled to be a function. Add a watch on color and update value of disabled.

$scope.$watch('color', function(){
  $scope.disabled = ($scope.color === 'red');
})
Sign up to request clarification or add additional context in comments.

Comments

0

No it won't, you can try something like using ng-change listener and assigning the scope

 <body ng-app="radioExample">
   <script>
      angular.module('radioExample', [])
        .controller('ExampleController', ['$scope', function($scope) {
          $scope.color = 'blue';
          $scope.disabled = false;

          $scope.foo = function(){
            if ($scope.color === 'red'){
            $scope.disabled = true;
          }
      }
        }]);
   </script>
   <form name="myForm" ng-controller="ExampleController">
      <input type="radio" ng-model="color" value="red" ng-change="foo()" >  Red <br/>
      <input type="radio" ng-model="color" value="green" ng-change="foo()"> Green <br/>
      <input type="radio" ng-model="color" value="blue" ng-change="foo()"> Blue <br/>
      <tt>color = {{color | json}}</tt><br/>
      <tt>{{disabled}}</tt><br/>
   </form>
</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.