触发指令链接更改另一个元素

时间:2015-01-21 07:50:05

标签: javascript angularjs angularjs-directive

我有这样的指令

app.directive('ppTypeahead', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            // get data using ajax and fill typeahead options
        }
    }
});

从服务器获取的数据取决于下拉选择。例如,select更改要在input的预先输入中显示的项目。

<select
    ng-options="col as col.col_name for col in meta_data.cols track by col.col_id"
    ng-model="row.col">
</select>

<input type="text" ng-model="row.value" pp-typeahead="{{row.col}}" />

如何在更改input时触发select的预先更新?

另外,我将{{row.col}}作为值传递给directive,是否正确?或者我应该做其他事情来从model内部访问directive。请注意,model不能像scope.model.col那样被访问。这是一个数组,所以我不知道我在哪一行。

更新

我发现在指令中执行$watch可能是一个解决方案。但我不想过度设计它并通过某些行动来实施它。在这种情况下ng-change的{​​{1}}。

1 个答案:

答案 0 :(得分:1)

您需要像这样绑定数据:

app.directive('ppTypeahead', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            col: '=ppTypeahead'
        }
        link: function (scope, element, attrs, ngModelCtrl) {
            // get data using ajax and fill typeahead options
        }
    }
});

然后你可以scope.$watch('col', function(){/*...*/})并调用你需要的任何功能。