隔离范围双向绑定不会及时更新以调用操作

时间:2016-05-24 18:41:55

标签: javascript angularjs angularjs-directive

我有一个角度指令,它作为一个控件,让客人从多个选择中挑选。选择一个选项时,会在父作用域中指定一个变量,并调用一个方法来指示“客人选择了某个东西。”

该指令如下所示:

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()调用之前传播。

1 个答案:

答案 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>