Here are some instructions for HTML:
<dropdown placeholder='' list='sizeWeightPriceArr' selected='selectedProductSize' property='size' value='size' style='width:60px;'></dropdown>
The variable selectedProductSize is a scope variable. The basic concept is that when a value is selected in the dropdown, this variable in the selected attribute saves all the changes. JavaScript:
.directive('dropdown', ['$rootScope', function($rootScope) {
return {
restrict: "E",
templateUrl: "templates/dropdown.html",
scope: {
placeholder: "@",
list: "=",
selected: "=",
property: "@",
value: "@"
},
link: function(scope, elem, attr) {
scope.listVisible = false;
scope.isPlaceholder = true;
scope.select = function(item) {
scope.isPlaceholder = false;
scope.selected = item[scope.value];
scope.listVisible = false;
};
scope.isSelected = function(item) {
return item[scope.value] === scope.selected;
};
scope.show = function() {
scope.listVisible = true;
};
$rootScope.$on("documentClicked", function(inner, target) {
if(!$(target[0]).is(".dropdown-display.clicked") && !$(target[0]).parents(".dropdown-display.clicked").length > 0) {
scope.$apply(function() {
scope.listVisible = false;
});
}
});
scope.$watch('selected', function(value) {
if(scope.list != undefined) {
angular.forEach(scope.list, function(objItem) {
if(objItem[scope.value] == scope.selected) {
scope.isPlaceholder = objItem[scope.property] === undefined;
scope.display = objItem[scope.property];
}
});
}
});
scope.$watch('list', function(value) {
angular.forEach(scope.list, function(objItem) {
if(objItem[scope.value] == scope.selected) {
scope.isPlaceholder = objItem[scope.property] === undefined;
scope.display = objItem[scope.property];
}
});
});
}
}
}])
The dropdown.html file is not relevant. When a selection is made, the scope.select function runs inside the directive, setting the selected value in
scope.selected = item[scope.value];
which works. In the controller, I tried to use $scope.$watch
to capture changes and trigger a function, but it did not work:
$scope.selectedProductSize = '';
$scope.$watch('selectedProductSize', function(value) {
...
});