简体   繁体   中英

How to change value of an array in knockout.js?

<div class="row">
    <div class="col-md-6" data-bind="visible: application.candidateMostRecentAcademic" style="display:none;">
        <span>Education:</span>
             <!-- ko if: application.candidateMostRecentAcademic != null -->
               <!-- ko with: application.candidateMostRecentAcademic[0] -->
                 <span data-bind="text: $data.degreeTypeName"></span>
                 <span data-bind="text: $data.institutionName"></span>
                 <span data-bind="text: $data.dateToYear"></span>
               <!-- /ko -->
             <!-- /ko -->
    </div>
</div>

I was going to make the the column visible only if application.candidateMostRecentAcademic (array) exists.

But I also wanted to add a condition for an array that has 0 length (which is not null).

So when I tried to do,

<div class="col-md-6" data-bind="visible: application.candidateMostRecentAcademic.length != 0" style="display:none;">

it gave me an error saying that it cannot access the "length" of a null object. So, what I am trying to do is, I want to set an array of length 0 to null so that it can just be invisible just like the null object.

How can I do this with knockout data-binding?

If I understand you correctly, you want your if statement to pass if the Array is not null and if it's length is not equal to 0 ?

If this is the case, you could do this in your template:

<div class="col-md-6" data-bind="visible: application.candidateMostRecentAcademic && application.candidateMostRecentAcademic.length !== 0">

Add another member in viewmodel called isColumnVisible and use this member to show and hide column.

var viewModel={
    isColumnVisible=true;
    loadData:function(){
        // code to load data;
        // application= something
        if(application.candidateMostRecentAcademic ===null){
            this.isColumnVisible=false;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM