简体   繁体   中英

How to output two dynamic variables that depend on each other

So for example :

Controller:

AllBooks[{
book1:{
hardcover{price:25.99},e-book{price:1.99}
}
},
book2:{
hardcover{price:60.00},e-book{price:2.99}
}];

$scope.bookchoice = function(selectedBook) {
$rootScope.choice = selectedBook;}


$scope.booktype = function(selectedType) {
$rootScope.type = selectedType;}

HTML:

<button ng-click="bookchoice(book1)">Book1</button>
<button ng-click="booktype(e-book)">E-Book</button>

{{choice.type.price}} <---this does not work

So I would like to know how to combine two dependent dynamic variables to access a part of an array and output the information

Thanks:)

Your AllBooks data is a bit weird. I am not sure if possible but I would reformat it like this. Then you can easily access the data using the key.

AllBooks = {
   book1:{hardcover{price:25.99},e-book{price:1.99}},
   book2:{hardcover{price:60.00},e-book{price:2.99}}
};

$scope.bookchoice = function(selectedBook) {
$rootScope.choice = AllBooks[selectedBook];}


$scope.booktype = function(selectedType) {
$rootScope.type = selectedType;}

You can access it like this

<button ng-click="bookchoice('book1')">Book1</button>
<button ng-click="booktype('e-book')">E-Book</button>

{{choice[type].price}} 

You might want to use quotes in your ng-click methods to avoid problems.

Controller

$scope.allBooks = { 
    book1: {
        hardcover: {
            price: 25.99
        },
        e_book: {
            price: 1.99
        }
    }, 
    book2: {
        hardcover: {
            price: 60.00
        },
        e_book: {
            price: 2.99
        }
    }
} ;

$scope.bookchoice = function ( selectedBook ) {
    $rootScope.choice = selectedBook;
}

$scope.booktype = function ( selectedType ) {
    $rootScope.choice.type = selectedType;
}

HTML

<button ng-click="bookchoice(allBooks.book1)">Book1</button>
<button ng-click="bookchoice(allBooks.book2)">Book2</button>
<button ng-click="booktype(choice.e_book)">E-Book</button>
<button ng-click="booktype(choice.hardcover)">Hardcover</button>

{{choice.type.price}}

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