简体   繁体   中英

how do i toggle the visibility of an html element using knockoutjs ?

i am using knockoutjs v3.1.0. i am trying to build a master-detail like view. the problem i am having is that elements are not showing (though they are hiding). my mock code is at http://jsfiddle.net/jwayne2978/qC4RF/3/

this is my html code.

<div data-bind="foreach: users">
<div>Row</div>
<div data-bind="text: username"></div>
<div data-bind="visible: showDetails">
    <div data-bind="text: address"></div>
</div>
<div> 
    <a href="#" 
        data-bind="click: $root.toggleDetails">
            Toggle Div
    </a>
</div>

this is my javascript code

var usersData = [
{ username: "test1", address: "123 Main Street" }, 
 { username: "test2", address: "234 South Street" }
];

var UsersModel = function (users) {
    var self = this;
    self.users = ko.observableArray(
        ko.utils.arrayMap(users, function (user) {
            return {
                username: user.username,
                address: user.address,
                showDetails: false
            };
        }));
    self.toggleDetails = function (user) {
        user.showDetails = !user.showDetails;
        console.log(user);
    };
};

ko.applyBindings(new UsersModel(usersData));

what's supposed to happen is that when a user clicks on the link, the corresponding HTML div should show. the console clearly shows that the property is being changed on the user object, but the HTML element's visibility is not changing. i also explicitly made the showDetails property observable, but that did not help.

showDetails : ko.observable(false)

any help is appreciated.

var UsersModel = function (users) {
var self = this;
//var flag=ko.observable(true);
self.users = ko.observableArray(
    ko.utils.arrayMap(users, function (user) {
        return {
            username: user.username,
            address: user.address,
            showDetails: ko.observable(false)  //it should be observable
        };
    }));
self.toggleDetails = function (user) {
    user.showDetails(!user.showDetails());
    console.log(user);
 };
};

Fiddle Demo

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