I am new to angularjs,
I have a textbox and I have a button and table:
whenever user click on add button the data in the textbox would be added to the table: here is the link to my code: code
everything works fine, but when it comes to autocomplete it starts acting funny, the autocomplete itselfe works fine but if for example add acti and the autocomplete suggests actionscript then if instead of writing the whole word you choose it from suggestins just he characters that you typed would be added, for example in this example acti instead of actionscript.
also here is my code:
<script>
var app = angular.module('app', []);
app.factory('Service', function() {
var typesHash = [ {
id :1,
name : 'lemon',
price : 100,
unit : 2.5
}, {
id : 2,
name : 'meat',
price : 200,
unit : 3.3
} ];
var localId = 3;
availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
var service = {
addTable : addTable,
getData : getData,
complete:complete
};
return service;
function complete(){
$( "#txt" ).autocomplete({
source: availableTags,
messages: {
noResults: '',
results: function() {}
}
});
}
function addTable(name,price) {
typesHash.push({id:localId++, name:name, price:price,unit:1});
}
function getData() {
return typesHash;
}
});
app.controller('table', function(Service) {
//get the return data from getData funtion in factory
this.typesHash = Service.getData();
//get the addtable function from factory
this.addTable = Service.addTable;
this.complete=Service.complete;
});
</script>
can anyone help? (also it is noteworthy that this is a smaller version of my project and for some reason I used factory)
Update:
one way is to use :
typesHash.push({id:localId++, name:$("#txt").val(), price:price,unit:1});
instead of :
typesHash.push({id:localId++, name:name, price:price,unit:1});
But I am sure there is a better way... Any idea?
The problem with your code is: angular doesn't aware of the update made by jquery plugin
So when you change the input text via
$( "#txt" ).autocomplete(...
the angular not aware about the change, so your "inputData
" not update!!To emphasize the problem, here updated plunker that print the
inputData
, as you can see when you select from autocomplete it still not updated, and because you take the info frominputData
to the table, you get the undesirable item!.The solution: you need to build a
directive
thatapply
your changes to angular.Look at this answer it's may help you
Hey sorry Hamed Minaee I am little late but here is the solution for you :-
You need to add
And remember to pass
$scope
to the service for controller updation by service.Plunker for you http://plnkr.co/edit/RqTDNRHpUicmFPsYsQR9?p=preview