I am currently developing a directive that acts as a wrapper for the freebase search widget using jQuery. This is my first attempt at creating a directive and I have encountered some challenges.
Here are the functionalities I am aiming for: 1. The ability to specify a language (using a two-letter code) for displaying search results as an attribute 2. The ability to define a function to be executed when an item is selected, passing relevant data from the selection
I have created a plunkr showcasing the directive here. The second functionality works smoothly, but I am facing difficulties with the language requirement and unsure of the reason behind it.
Passing in the language code works perfectly when done statically (without interpolation):
if(attrs.lang){
language = attrs.lang;
}
However, I am unable to make it work when trying to pass in the value like this:
attrs.$observe('lang', function(value) {
if(value === ""){
language = 'en';
} else {
console.log("lang val " + value);
language = value;
}
});
Any insights on why this approach is not functioning properly? I would greatly appreciate any advice.
The current state of the directive is as follows:
directive('suggest', function($http) {
var language;
return {
restrict: 'E',
template: "<input type='text'>",
replace:true,
scope:{
selectData:'=',
onSelect:'&'
},
link: function(scope, element, attrs) {
attrs.$observe('lang', function(value) {
if(value === ""){
language = 'en';
} else {
console.log("lang val " + value);
language = value;
}
});
if(attrs.lang){
language = attrs.lang;
}
$(element).suggest({
"lang": language
})
.bind("fb-select", function(e, info) {
console.log(info);
scope.onSelect({data:info});
console.log("language: " + language);
scope.$apply(function(){
console.log("hello apply here");
scope.selectData = info;
});
});
}
};
});