0

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

2
  • 1
    var x = $scope.lineData[0] !== undefined ? $scope.lineData[0].line : 0; Commented Dec 26, 2016 at 13:53
  • @Satpal : Thank you.. Its working.. Commented Dec 26, 2016 at 14:04

3 Answers 3

1

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";
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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/

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.