Filter Data Using Knockout JS - javascript

I have static array that have 2 set of data.
I have make 2 part of the one div and on right side show all list from array and on left side nothing.
On right side have put + sign on button, on it's click that record came on left side div and working fine and at that time the plus sign become minus when that record came on left side, when click on minus sign again that record removed from left side. Just like toggle.
Now I want to filter the right side of list using textbox.
It will search on 2 columns i.e. code and title.
but how to make filter I don't know.
HTML Code :
<div class="col-md-6">
<div class="col-md-4">
<input type="text" required id="filterD" class="form-control" data-bind=""/>
</div>
<!-- ko foreach: controlFields -->
<div class="row">
<div class="col-md-11 table-bordered">
<div class="form-group" style="padding-top: 3px;">
<div class="col-md-2" data-bind="text:code">
</div>
<div class="col-md-7" data-bind="text:title">
</div>
<div class="col-md-1" data-bind="text:i1">
</div>
<div class="col-md-1" data-bind="text:i2">
</div>
<div>
<!-- ko ifnot : viewFlag -->
<button class="btn-primary btn-xs" data-bind="click: $root.addField">
<i class="glyphicon glyphicon-plus-sign"></i>
</button>
<!-- /ko -->
<!-- ko if : viewFlag -->
<button class="btn-primary btn-xs" data-bind="click: $root.removeField">
<i class="glyphicon glyphicon-minus-sign"></i>
</button>
<!-- /ko -->
</div>
</div>
<!-- ko foreach: subFields -->
<div style="padding-top: 3px" class="form-group" data-bind="attr:{'title':description()}">
<div class="col-md-2">
</div>
<div style="border-top: 1px solid #ddd; " class="col-md-2" data-bind="text:code">
</div>
<div style="border-top: 1px solid #ddd; " class="col-md-7" data-bind="text:title">
</div>
<div>
<button class="btn-primary btn-xs"><i class="glyphicon glyphicon-plus-sign"></i></button>
</div>
</div>
<!-- /ko -->
</div>
</div>
<br />
<!-- /ko -->
</div>
JavaScript :
var exports = {},
ViewModel, ControlField , SubField;
SubField = function(code, title,data,description){
var self = this;
self.code = ko.observable(code);
self.title = ko.observable(title);
self.data = ko.observable(data);
self.description = ko.observable(description);
};
ControlField = function(code, title, i1, i2){
var self = this;
self.code = ko.observable(code);
self.title = ko.observable(title);
self.i1 = ko.observable(i1);
self.i2 = ko.observable(i2);
self.subFields = ko.observableArray([]);
self.viewFlag = ko.observable(false);
};
ViewModel = function(data) {
var self = this;
self.controlFields = ko.observableArray([]);
var controlField = new ControlField("100","BookTitle","0","1");
self.controlFields.push(controlField);
controlField.subFields().push(new SubField("a","Title","JAVA","For Entering Item Title Data"));
controlField.subFields().push(new SubField("p","Section","2","For Section"));
var controlField1 = new ControlField("245","Author","1","0");
self.controlFields.push(controlField1);
controlField1.subFields().push(new SubField("a","Name","Herbert","Name of The Author"));
controlField1.subFields().push(new SubField("d","Place","Ontario","Place of Author"));
self.addField = function(field){
field.viewFlag(true);
};
self.removeField = function(field){
field.viewFlag(false);
};
};
I want that when I type any character in input=text it will filter data and then show.
Any suggestion on this.
Here's Screen of this code :

You can use ko.computed for filtering the data.
//filter html binding
<input type="text" required id="filterD" class="form-control" data-bind="value:filter,valueUpdate: 'keyup'" />// use valueUpdate binding
//bind filter to filter text
self.filter = ko.observable();
//Use filteredList in html binding instead of controlFields
self.filteredList = ko.computed(function () {
var filter = self.filter(),
arr = [];
if (filter) {
ko.utils.arrayForEach(self.controlFields(), function (item) {
if (item.code() == filter || item.title() == filter) {
arr.push(item);
}
});
} else {
arr = self.controlFields();
}
return arr;
});
Fiddle Demo
//sorry for ui part(Html alignment) in demo.

Related

I can´t remove the last item of array

I can remove any item of array unless the last one. I also use angularjs to show information in the view. I don´t know what is happening with the last item of this array. Please, anyone can help me?
Here is HTML:
<div class="row">
<div class="col-md-12">
<h4><strong>Documento {{index + 1}} de {{documentos.length}}:</strong> {{documentos[index].nome}}</h4>
<iframe style="background: #ccc;" ng-show="exibirPreview" frameborder="0" ng-src="{{versaoLink}}" width="100%" height="300px"></iframe>
<div class="alert alert-warning" ng-hide="exibirPreview">
#Html.Raw(Resources.Dialog.SignDocuments.TypeDocumentCanNotPreDisplayed)
</div>
<hr />
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<button class="btn btn-default" type="button" ng-click="RemoveDoc(index)"><i class="fa fa-fw fa-times"></i> #Resources.Common.RemoveDocList</button>
</div>
</div>
</div>
Here is js/angularjs
$scope.documentos = [
{nome:"document1", chave: "8F65579E3737706F", extensao:".pdf"},
{nome:"document2", chave: "8F65579E3730007F", extensao:".pdf"},
{nome:"document3", chave: "8545579E3737706F", extensao:".pdf"},
{nome:"document4", chave: "8555579E3730007F", extensao:".pdf"}
]
$scope.ViewLink = function () {
var versao = $scope.documentos[$scope.index];
$scope.exibirPreview = versao.extensao == ".pdf" || versao.extensao == ".txt";
if (!$scope.exibirPreview) {
$scope.versaoLink = '';
} else {
$scope.versaoLink = '/Documento/VersaoView?chave=' + versao.chave;
}
};
$scope.ViewLink();
$scope.RemoveDoc = function (index) {
$scope.documentos.splice(index, 1);
$scope.ViewLink();
};
Or Plunker
In your HTML you are preventing the deletion of the last element:
<div class="pull-right btn-row" ng-show="documentos.length > 1">
<!-- -->
</div>
documentos.length > 1 means "hide when it reaches one item in the array".
It should be documentos.length == 0.
It's either this or your index value starts from 1 and not from 0.
The simplest solution would be to change your remove function to take in the document instead of the index. Try this:
$scope.RemoveDoc = function(document) {
var index = $scope.documents.indexOf(document);
$scope.documents.splice(index, 1);
}
in view:
<button class="btn" type="button" ng-click="RemoveDoc(document)">Delete</button>

How can I Add/Edit on same page in Angular

There are two types of data I'm displaying on single page, one is Insert form and second is where the data is displayed with the help of Angular dataTables, now what I want to do is when I click on Edit I wana display the Data within the Insert form Fields also change the Save button from Save to Update... I've tried it but I'm getting this error although its displaying the data in console.
controller.js:1356 24
controller.js:1363 Colony 02 2
angular-1.4.8.js:12520 TypeError: Cannot set property 'colony_name' of undefined
NOTE: Insert, Delete, Displaying Data is working fine.
Here is my HTML PAGE
<div class="row-fluid" ng-controller="colony_Controller">
<div class="span12">
<div class="span6">
<!-- WIDGET START -->
<div class="widget TwoWidgetsInOneFix">
<!-- Widget Title Start -->
<div class="widget-title">
<h4><i class="icon-reorder"></i>Add Colony</h4>
<span class="tools">
<!-- -->
</span>
</div>
<!-- Widget Title End -->
<!-- Widget Body Start -->
<div class="widget-body">
<form class="form-horizontal">
<div class="control-group">
<div class="small-bg-half">
<label class="control-label">Colony Name</label>
<div class="controls">
<input type="text" class="input-xlarge" id="" autofocus required name="colony_name"
ng-model="field.colony_name" > <!-- ng-->
<span class="help-inline" id="help-inline" style="color:red;"></span>
</div>
</div>
</div>
<div class="control-group">
<div class="small-bg-half">
<label class="control-label">Colony Type</label>
<div class="controls">
<select data-toggle="status" class="select select-default mrs mbm input-xlarge" name="colony_type" id="colony_type" ng-model="field.colony_type_id" required> <!-- ng -->
<option value="">--Select Colony Type--</option>
<option ng-repeat="colony in es_colony_type" value="{{colony.es_colony_type_id}}">{{colony.es_colony_type_name}}</option>
</select>
</div>
</div>
</div>
<div class="form-actions">
<button type="button" class="btn btn-success" ng-click="InsertData()"> <!-- ng -->
<i class="icon-plus icon-white"></i> Save</button>
</div>
</form>
</div>
<!-- Widget Body End -->
</div>
<!-- WIDGET END -->
</div>
<div class="span6">
<!-- WIDGET START -->
<div class="widget TwoWidgetsInOneFix">
<!-- Widget Title Start -->
<div class="widget-title"> <!-- ng -->
<h4><i class="icon-reorder"></i>List Of Colony</h4>
<span class="tools">
<!-- -->
</span>
</div>
<!-- Widget Title End -->
<!-- <div id="alert-2" flash-alert active-class="in alert" class="fade">
<strong class="alert-heading">Boo!</strong>
<span class="alert-message">{{flash.message}}</span>
</div> -->
<!-- Widget Body Start -->
<div class="widget-body">
<div ng-controller="colony_Controller as Main_Module">
<table class="table table-striped table-bordered" align="center" datatable="" dt-options="Main_Module.dtOptions" dt-columns="Main_Module.dtColumns" class="row-border hover">
</table>
</div>
</div>
</div>
<!-- Widget Body End -->
</div>
<!-- WIDGET END -->
</div>
Here is my Controller
Main_Module.controller('colony_Controller', function add_house_Controller(flash, $window, $scope, $http, $compile, DTOptionsBuilder, DTColumnBuilder, bootbox, SimpleHttpRequest, DelMainRecPicRecUnlinkPic, message)
{
$http.get('http://localhost:3000/api/SELECT/es_colony_type').success(function(data)
{
$scope.es_colony_type = data.es_colony_type;
});
/********************************** FETCH DATA END *********************************/
/********************************** INSERT DATA START ********************************/
$scope.InsertData = function()
{
var values = $scope.field;
SimpleHttpRequest.Insert('POST','INSERT', 'es_colony', values)
.then(function successCallback(response)
{
if(!response.data.Error)
{
message.successMessageForInsert("<strong>Successfull !</strong> Colony Details Inserted");
setTimeout(function()
{
$window.location.reload();
}, 3500);
// flash.to('alert-1').success = 'Only for alert 1';
}
else
{
message.failedMessageForInsert("<strong>Error !</strong> Data Insertion Failed");
}
},
function errorCallback(response)
{
message.failedMessageForInsert("<strong>Error!</strong> Data Insertion Failed !");
});
};
/********************************** INSERT DATA END **********************************/
/********************************** DISPLAY DATA START *******************************/
var vm = this;
vm.dtOptions = DTOptionsBuilder
.fromFnPromise(function()
{
return $http.get('http://localhost:3000/api/SELECT/es_colony')
.then(function(response)
{
return response.data.es_colony;
});
})
.withOption('order', [0, 'asc'])
.withDisplayLength(5)
.withPaginationType('simple_numbers')
.withOption('createdRow', function(row, data, dataIndex)
{
$compile(angular.element(row).contents())($scope);
})
vm.dtColumns =
[
DTColumnBuilder.newColumn('es_colony_name').withTitle('Colony'),
DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable().withOption('width', '31%')
.renderWith(function(data, type, full, meta)
{
return '<button class="btn btn-primary" ng-click="edit_records(' + data.es_colony_id + ')">' +
'<i class="icon-edit"></i> Edit' + '</button> ' +
'<button class="btn btn-danger" ng-click="DeleteRecord(' + data.es_colony_id + ')">' +
'<i class="icon-remove icon-white"></i> Delete' + '</button>';
})
];
/********************************** DISPLAY DATA END *********************************/
/********************************** DELETE DATA START ********************************/
// $scope.hideRow = [];
$scope.DeleteRecord = function(id)
{
bootbox.confirm("Are you sure you want to delete this Record ?", function (confirmation)
{
if(confirmation)
{
DelMainRecPicRecUnlinkPic.DeleteIt('', id, true, 'es_colony', 'es_colony_id')
{
setTimeout(function()
{
$window.location.reload();
}, 3500);
};
}
});
};
$scope.edit_records = function(id)
{
// PassId.id = id;
console.log(id);
SimpleHttpRequest.SelectByID('GET', 'SELECTBYID', 'es_colony', 'es_colony_id', id)
.then(function successCallback(response)
{
var data = response.data.es_colony[0];
console.log(data.es_colony_name, data.es_colony_type_id);
$scope.ufield.ucolony_name = data.es_colony_name;
$scope.ufield.colony_type_id = data.es_colony_type_id;
});
};
/********************************** DELETE DATA END **********************************/
});
In your template, you have an input with ng-model="field.colony_name", but in your controller you never defined $scope.field. You do assign the value var values = $scope.field inside the $scope.InsertData function, but that will just set values to undefined.
Try initializing the variable by adding $scope.field = {} to the beginning of your controller, for starters. That will resolve the error you are getting.
Here is the code that may help you.
Html:
<div ng-app="myApp" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<input type="text" ng-model="choice.name" name="" placeholder="Enter mobile number"> <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }}
</div>
</div>
Js:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
Also CSS:
fieldset{
background: #FCFCFC;
padding: 16px;
border: 1px solid #D5D5D5;
}
.addfields{
margin: 10px 0;
}
#choicesDisplay {
padding: 10px;
background: rgb(227, 250, 227);
border: 1px solid rgb(171, 239, 171);
color: rgb(9, 56, 9);
}
.remove{
background: #C76868;
color: #FFF;
font-weight: bold;
font-size: 21px;
border: 0;
cursor: pointer;
display: inline-block;
padding: 4px 9px;
vertical-align: top;
line-height: 100%;
}
input[type="text"],
select{
padding:5px;
}
Html
<div ng-app="albumShelf">
<div ng-controller="MainCtrl">
<div style="float:left;">
<select ng-options="b.title for b in albums" ng-model="currentAlbum" ng-change="onChange()">
<option value="">New album...</option>
</select>
</div>
<div style="float:left;">
<form>
<input type="text" ng-model="editing.title">
<br>
<input type="text" ng-model="editing.artist">
<br>
<input type="submit" value="{{ currentAlbum.title ? 'Update' : 'Save' }}" ng-click="addOrSaveAlbum()">
</form>
</div>
</div>
</div>
Js:
var app= angular.module('myApp', [])
.controller('MainCtrl', ['$scope', function($scope/*, albumFactory*/) {
$scope.editing = {};
$scope.albums = [
{ id: 1, title: 'Disorganized Fun', artist: 'Ronald Jenkees' },
{ id: 2, title: 'Secondhand Rapture', artist: 'MS MR' }
];
$scope.addOrSaveAlbum = function() {
if ($scope.currentAlbum) {
$scope.currentAlbum.title = $scope.editing.title;
$scope.currentAlbum.artist = $scope.editing.artist;
}else {
$scope.albums.push({ title: $scope.editing.title, artist: $scope.editing.artist });
}
$scope.editing = {};
};
$scope.onChange = function() {
if ($scope.currentAlbum) {
$scope.editing.title = $scope.currentAlbum.title;
$scope.editing.artist = $scope.currentAlbum.artist;
}else {
$scope.editing = {};
}
};
}])

Is JQuery breaking my functionality?

I am making an app, the user can either select an item or use their camera to get the qr code which translates into an item's ID.
The problem is that I think some JQuery is messing with my scope from working properly.
I have to get the QR code by listening to an innerHtml change, once it changes (DOMSubtreeModified) the following occurs.
var index = 0;
$('#result').one('DOMSubtreeModified', function(e) {
var code = "";
if (e.target.innerHTML.length > 0) {
code = e.target.innerHTML;
$scope.ToRun(code);
}
});
$scope.ToRun = function(code) {
for (i = 0; i < $scope.plantList.length; i++) {
if ($scope.plantList[i].plantcode == code) {
index = i;
break;
}
}
$scope.currentPlant = $scope.plantList[index];
$scope.plantDetails = false;
$scope.searchDetails = true;
}
For some reason the following does not have any effect on my ng-classes. As when an item is selected I hide the input dialogs, and show the result one.
$scope.plantDetails = false;
$scope.searchDetails = true;
But when a user selects the item manually it works just perfectly. (the items have an ng-click on it)
$scope.viewPlant = function(plant) {
$scope.currentPlant = plant
$scope.plantDetails = false;
$scope.searchDetails = true;
};
And the above works fine, with the ng-click. So why won't my new function that listens for an innerHtml change work?
HTML snippet
<div ng-class="{ 'hidden': searchDetails }">
<!-- CHOOSE INPUT TYPE -->
<div class="form-group" style="margin-bottom:0px">
<div class="btn-group btn-group-justified">
<div class="btn-group">
<button type="button" class="btn btn-default" ng-click="digits = false; qr = true">Plant Code</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-default" ng-click="digits = true; qr = false">QR Code</button>
</div>
</div>
</div>
<br />
<!-- QR CODE INPUT -->
<div ng-class="{ 'hidden': qr }">
<img id="blah" src="./images/placeholder.png" />
<span class="btn btn-default btn-file">
<i class="glyphicon glyphicon-camera"></i>
<input type="file" onchange="readURL(this);handleFiles(this.files)">
</span>
<div id="result">xxxxxx</div>
<canvas id="qr-canvas" width="800" height="600"></canvas>
</div>
<!-- MANUAL SELECTION INPUT -->
<div ng-class="{ 'hidden': digits }">
<input ng-model="search.$" style="width:100%; font-size:30px; text-align:center" placeholder="Plant Code" />
<div style="overflow: auto; max-height:250px">
<table class="table table-striped" style="background-color:lightblue">
<tr ng-repeat="plant in plantList | filter:search" ng-click="viewPlant(plant)" style="cursor:pointer">
<th>{{plant.name}}</th>
<th>{{plant.plantcode}}</th>
</tr>
</table>
</div>
</div>
<div>
</div>
</div>
<div ng-class="{ 'hidden': plantDetails }">
// results - this should appear when one of the above is entered.
// works for manual selection, but not qr code
</div>
Just confused on why my QR input will not fire off the change-class options to hide the searchDetails div and show the plantDetails div
EDIT: Doing a small test, it seems that my class variables are indeed not updating at all. I just put the values at the bottom of my page and they do not update when hitting the block of:
$scope.plantDetails = false;
$scope.searchDetails = true;
You need to let Angular know about the change. Add this at the end of your method and let me know if it works.
$scope.$apply();

how to generate list dynamically in angular.js

can you please tell me how to create list dynamically in angulat.js..Actullly I am able to make list when user press add button and fill the field .
In other words ,Please check this fiddle whenever you fill the fields it generate a row.And you can get Id when you click the row .Fiddle http://jsfiddle.net/wc4Jm/6/
Now I am trying to do this using bootstrap model .in other words on button click first I show a pop up screen then there is "add" button .on click that it generate the row.but I am getting "undefined".My I insert the model div inside the controller ? here is
http://jsbin.com/vubojoxo/4/
Why I am getting this error ?
XMLHttpRequest cannot load file:///C:/Users/asd/Desktop/angular/angularproject/dialog.html. Received an invalid response. Origin 'null' is therefore not allowed access.
I am getting this error when I used plunker..and run in my desktop ..
I make this html ?
<!doctype html>
<html ng-app="plunker">
<head>
<script src="angular.js"></script>
<script src="ui-bootstrap-tpls-0.2.0.js"></script>
<link href="bootstrap-combined.min.css" rel="stylesheet">
<script src="index.js"></script>
</head>
<body>
<div ng-controller="DialogDemoCtrl">
<a class="btn" data-toggle="modal" href="" ng-click="openPopupScreen()">Add Contend</a>
</div>
</body>
</html>
....
Dialog.html
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h1>Add Element</h1>
</div>
<div class="modal-body">
<form >
<label>Name:</label><input type="text" class="span3" ng-model="activeItem.name"></br>
<label>Content Name:</label><input type="password" class="span3" ng-model="activeItem.content"></br>
<button type="submit" class="btn btn-success" ng-click="addItem()">Add In List</button>
<button type="reset" class="btn ">Clear</button>
</form>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal" aria-hidden="true">close</a>
</div>
js code:
var myApp = angular.module('plunker', ['ui.bootstrap']);
myApp.controller('DialogDemoCtrl', function($scope,$dialog) {
$scope.items = [];
$scope.activeItem = {
id:'',
name: '',
content: ''
};
$scope.addItem = function () {
$scope.activeItem.id = $scope.items.length + 1;
$scope.items.push($scope.activeItem);
$scope.activeItem = {}; /* reset active item*/
};
$scope.getId = function (item) {
alert('ID: '+item.id);
};
$scope.openPopupScreen = function () {
alert('Check Open pop up screen');
$dialog.dialog({}).open('dialog.html');
};
});
Check this Plunker
In this example i used angular-ui library which wraps bootstrap's modal to angular
based on this StackOverflow Answer
ModalDemoCtrl
$scope.items = [];
$scope.getId = function(item) {
alert('ID: ' + item.id);
};
// This opens a Bootstrap modal
$scope.open = function() {
var modalInstance = $modal.open({
template: $scope.modal_html_template,
controller: ModalInstanceCtrl
});
modalInstance.result.then(function(newItem) {
// On modal success
newItem.id = $scope.items.length + 1;
$scope.items.push(newItem);
}, function() {
// On modal cancelation
});
}
ModalInstanceCtrl
$scope.name = '';
$scope.content = '';
$scope.ok = function() {
var response = {
'name': $scope.name,
'content': $scope.content
};
$modalInstance.close(response);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
HTML
<body>
<div ng-controller="ModalDemoCtrl">
<div inner-html-bind="" inner-html="modal_html_template" class="hidden">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.name" placeholder="Enter Name">
</div>
<div class="form-group">
<label>Content</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.content" placeholder="Enter Content">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</div>
<div class="container">
<h2>Modal Example https://stackoverflow.com/questions/24988561</h2>
<button class="btn" ng-click="open()">Open Modal</button>
<div>
<ul>
<li ng-repeat="item in items">
<a ng-click="getId(item)">{{ item.id }} | {{ item.name + ' ' + item.content }}</a>
</li>
</ul>
</div>
</div>
</div>
</body>

KnockoutJS Not Populating $root observable inside the "With" Binding Context

I've searched and searched for an answer, so hope I haven't duplicated this anywhere.
I am using ASP .NET MVC5, with KnockoutJS as my ORM.
For some reason, data isn't being populated in the DOM when I try to reference back to the ViewModel using the $root binding context (Once inside the "with" binding context)
The with binding context is declared in a normal mvc view razor page, however I am using the $root binding context inside a partial view which is loaded into the main view.
Has anyone had any problems like this or can spot my error? I will paste my viewmodel and html code below.
ViewModel
var ProfileViewModel = function () {
var self = this;
this.Member = ko.observable(); - With Binding to this
this.SocialNetworks = ko.observableArray();
this.Skills = ko.observableArray();
this.SkillsFilter = ko.observable(""); - Trying to access these from root
this.FilteredSkills = ko.observableArray();
this.References = ko.observableArray();
this.Has = function (has_what) {
if (has_what) {
if (has_what.length > 0) {
return true;
} else {
return false;
}
}
return false;
};
$.getJSON("/doitgrad/api/member/CameronPearce91", function (allData) {
self.Member(new DoItGrad.Objects.Member(allData, true));
self.FilteredSkills = ko.computed(function () {
return ko.utils.arrayFilter(self.Skills(), function (item) {
var filter = self.SkillsFilter(),
doesnthaveskill = (jQuery.inArray(item, self.Member().details.skills()) == -1),
containsfiltertext = (item.title().indexOf(filter) > -1);
if (filter != "") {
return (doesnthaveskill && containsfiltertext);
} else {
return doesnthaveskill;
}
});
});
})
$.getJSON("/doitgrad/api/skill/", function (allData) {
var mappedSkills = $.map(allData, function (item) { return new DoItGrad.Objects.Skill(item); });
self.Skills(mappedSkills);
});
}
var model = new ProfileViewModel();
ko.applyBindings(model);
MVC View
<section id="profile-details" data-bind="with: Member">
<section id="profile-cover">
<!-- ko if: details.images.cover() == null -->
<img src="/DoitGrad/Content/images/Profile/default_cover.jpg">
<!-- /ko -->
<!-- ko ifnot: details.images.cover() == null --><!-- /ko -->
<section class="change-cover">Change cover photo</section>
<section id="profile-picture">
<!-- ko if: details.images.profile() == null -->
<img src="/DoitGrad/Content/images/Profile/default_avatar.png">
<!-- /ko -->
<!-- ko ifnot: details.images.profile() == null --><!-- /ko -->
<h2 id="profile-name" data-bind="text: title">Cameron Pearce</h2>
<section id="profile-username" data-bind="text: details.username">CameronPearce91</section>
</section>
</section>
<section id="profile-wrapper">
<section id="profile-about" data-bind="text: description">Since I have been at uni, I believe I have achieved a lot. I took a year out of my studies to do a work placement year with Xerox based in Welwyn Garden City, primarily focusing on developing C# Web Applications on the MVC framework. It was the best thing I could have done for my career I believe, I have certainly learnt a lot.</section>
#Html.Partial("partialname")
Partial View
<section class="profile-detail-holder">
<section class="add" data-form="addSkill">+</section>
<h2 class="profile-detail-header">Skill Wall</h2>
<ul id="profile-skillwall" data-bind="foreach: details.skills()"></ul>
</section>
<section class="dialog-form" data-form="addSkill">
<section class="form-cover grey"></section>
<section class="form-content">
<section class="form-wrap">
<section class="form-close">x</section>
<header class="form-header">Add Skill</header>
<section class="form-body">
<form id="dig-member-addskill" class="area" method="post" action="#">
<input type="text" data-bind="text: $root.SkillsFilter" placeholder="Filter list of skills..." class="ui-textbox"></input>
<ul data-bind="foreach: $root.FilteredSkills"></ul>
<section class="ui-button submit">
<input type="submit" value="Add">
</section>
</form>
</section>
</section>
</section>
</section>
If anyone needs anymore information, feel free to ask.
I think I've spotted it, and it's fairly simple:
<input type="text" data-bind="text: $root.SkillsFilter" placeholder="Filter list of skills..." class="ui-textbox"></input>
you are using a text-binding on the input field, so updating the input won't change the observable. Use a value-binding instead:
<input type="text" data-bind="value: $root.SkillsFilter" placeholder="Filter list of skills..." class="ui-textbox"></input>

Categories

Resources