Ternary Operator Angular JS

879 views Asked by At

I have $scope.lineData[0].line in my controller. I want to check $scope.lineData[0] != undefined , If so then $scope.lineData[0].line else just "0" value to add. How can do this with angular JS ?

Can anyone help me to do this? Thanks in advance..

3

There are 3 answers

0
Surya Purohit On BEST ANSWER

In Template we would do it something like

{{ lineData[0] ? lineData[0].line : "0" }}

In Controller, we'll be doing

var some_value = $scope.lineData[0] ? $scope.lineData[0].line : "0";
0
Michael Sacket On

This should do it:

{{ $scope.lineData[0] ? $scope.lineData[0].line : "0" }}

Update

You could also simply do:

{{ $scope.lineData[0].line || "0" }}

Angular will coalesce from left to right, the first non-null/undefined value.

0
Nikhil Maheshwari On

You can use it according to your usecase, Few of those might be :

1) ex. <input ng-value="getLine()" />

2) ex. <div>{{lineData[0] ? lineData[0].line : "0"}}</div>

3) ex. in Controller, var value = $scope.lineData[0] ? $scope.lineData[0].line : "0";

HTML :

<div ng-controller="MyCtrl">
    <input ng-value="getLine()" />
    <div>{{lineData[0] ? lineData[0].line : "0"}}</div>
</div>

JavaScript :

var myApp = angular.module('myApp',[]);


function MyCtrl($scope) {

    $scope.lineData = [{
        line : 3,
    }];

    $scope.getLine = function() {
        return $scope.lineData[0] ? $scope.lineData[0].line : "0";
    }

}

JSFiddle : http://jsfiddle.net/nikdtu/v6ezygy2/