我有一些关于html的指令:
<dropdown placeholder='' list='sizeWeightPriceArr' selected='selectedProductSize' property='size' value='size' style='width:60px;'></dropdown>
selectedProductSize =&gt;范围变量。基本理念=&gt;我在下拉列表中选择了一些值,并且所选属性中的此变量保存所有更改。 JS:
.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];
}
});
});
}
}
}])
dropdown.html不相关。当我选择scope.select
函数在指令内运行并在scope.selected = item[scope.value];
设置选定值时。这是工作。然后在控制器中我尝试编写$scope.$watch
以捕获更改并运行函数但它不会工作:
$scope.selectedProductSize = '';
$scope.$watch('selectedProductSize', function(value) {
...
});
答案 0 :(得分:1)
您不需要用户$watch
您可以通过双向数据绑定将变量传递给指令
$scope.my_var = ''
指令html
myvar=my_var
指令
scope: {
myvar: '='
}
$scope.my_var
将绑定到指令myvar
,因此您的指令中任何时候scope.myvar
发生更改,$scope.my_var
也会在您的控制器中更新