knockout.js - knockoutjs - accessing $parent/$root inside foreach binding -
here plunker code working on. have defined vm looks this.
var employee = function(fname,lname){ var self= this; self.fname = ko.observable(fname); self.lname = ko.observable(lname); self.selectedelement = ko.observable('default value'); } var vm = function(){ var self = this; self.employees = new ko.observablearray([]); self.selectedelement = ko.observable(-1); var e1 = new employee('f1','l1'); var e2 = new employee('f2','l2'); self.employees.push(e1); self.employees.push(e2); }; ko.applybindings(vm,container);
and code display list of employees
<body id="container"> <h1>empoyees</h1> <div> <div data-bind="foreach: employees"> <h4 data-bind="text: 'employee' + $index()"></h4> <span>first name :</span> <span data-bind="text: fname"></span> <br/> <span>last name :</span> <span data-bind="text: fname"></span> <br/> <span data-bind="text: selectedelement()"></span> <!-- want access parents 'selectedelement' i.e. vm.slectedelement() --> <!--i tried below code causing binding error.--> <!-- <span data-bind="text: $parent.selectedelement()"></span> --> <br/> </div> </div>
note lass 'employee
' , main view model 'vm
' both has identical property named ( selectedelement
)
now inside foreach binding trying access 'selectedelement
' property of root/parent context because inside foreach ko accessing 'selectedelement' property of 'employee' class.
i tried using $root
, $parent
keywords reach parent element property causing binding error.
am missing anything? here plunker link again.
you never creating instance of root view model. change initial call to
ko.applybindings(new vm(),container);
https://plnkr.co/edit/wrkfnji9jl9rj2unbgqp?p=preview
when that, either $root
or $parent
work expected.
Comments
Post a Comment