我有一个角度指令,它作为一个控件,让客人从多个选择中挑选。选择一个选项时,会在父作用域中指定一个变量,并调用一个方法来指示“客人选择了某个东西。”
该指令如下所示:
module.directive("myThingpicker", function () {
return {
restrict: "E",
scope: {
items: "=",
item: "=",
selected: "&"
},
templateUrl: "/templates/thing-picker.html",
controller: function ($scope) {
$scope.selectItem = function (item) {
$scope.item = item;
$scope.selected();
console.log ("The user picked an item:", item);
};
}
};
});
模板很简单:<li>
元素使用带有ng-repeat="x in items"
指令的ng-click="selectItem(x)"
生成。
问题是当selected
被调用时,item
尚未将其值传递给父作用域。测试绑定值会导致undefined
。再次单击(并进行第二次selected()
调用会显示上一次点击的值。
鉴于这一事实,我要么是两种可能的解决方案之一:
selected
selected
,我会收到错误无法使用'in'运算符来搜索... item
的值在selected()
调用之前传播。答案 0 :(得分:0)
我会重写你的$scope.selected();
以接受一个可通过的参数item
,这样当通过selected
范围的函数执行时,它就会有它正在寻找的数据。然后回调可以将项目分配给控制器中的范围变量,如果这是您希望它做的事情。
<强>指令
module.directive("myThingpicker", function () {
return {
restrict: "E",
scope: {
items: "=",
selected: "&"
},
templateUrl: "/templates/thing-picker.html",
controller: function ($scope) {
$scope.selectItem = function (item) {
$scope.selected(item);
console.log ("The user picked an item:", item);
};
}
};
});
<强>控制器
module.directive("fooController", function ($scope) {
$scope.model = []; //example of your items
$scope.selectCallback = function(item) {
// your code goes here
};
});
<强>标记
<my-thingpicker items="model" selected="selectCallback"></my-thingpicker>