$scope和 ng 模型在同一指令中

$scope and ng-model in the same directive

本文关键字:指令 模型 scope ng      更新时间:2023-09-26

我有一个指令,它保存在控制器的模型中。它是一个"文本按钮"(根据要求),只是一个只读文本框。每个"行"和 13 个"行"有三个文本按钮。

我需要拉出一个选择模式并根据单击的内容加载一些数据,以便可以进行新的选择。

虽然控制器上的模型发生了变化,但我不知道在弹出选择模式时发生了什么变化。

型:

$scope.Lines = {
    "eg1": { one: '', two: '', three: '' },
    "eg2": { one: '', two: '', three: '' },
    "eg3": { one: '', two: '', three: '' },
    "eg4": { one: '', two: '', three: '' },
    ... 9 more ...
};

命令:

.directive('textButton', function () {
    return {
        restrict: 'E',
        require: 'ngModel',
        link: function ($scope, elm, attrs, ctrl) {
            elm.on('click', function () {
                $scope.popModal(this); //<--I want the ng-model here!
            });
        },
        template: '<input type="text" readonly="readonly" class="form-control" />'
    };
});

视图:

<ul>
    <li> <text-button ng-model="Lines.eg1.one"></text-button> </li>
    <li> <text-button ng-model="Lines.eg1.two"></text-button> </li>
    <li> <text-button ng-model="Lines.eg1.three"></text-button> </li>
<ul>
<ul>
    <li> <text-button ng-model="Lines.eg2.one"></text-button> </li>
    <li> <text-button ng-model="Lines.eg2.two"></text-button> </li>
    <li> <text-button ng-model="Lines.eg2.three"></text-button> </li>
<ul>
... 11 more ...

我看过$watch和$scope.watch,但似乎没有什么能告诉我特定模型中发生了哪些变化。

https://stackoverflow.com/a/15113029/1913371

最后,您需要隔离指令的范围,以便有机会了解每行的ngModel

scope: {
   ngModel: '@',
   popModal: '='
}

然后你可以在回调中使用它:

elm.on('click', function () {
    $scope.popModal($scope.ngModel); //<--you get the ng-model here!
});

但是,这意味着您还将无法访问popModal()我想这是在控制器作用域中定义的。要解决此问题,您需要将其作为第二个参数提交(我将其命名为 pop-modal):

<text-button ng-model="Lines.eg1.one" pop-modal="popModal"></text-button>
将它们

结合在一起,这里有一个使用 Angular 1.2 的 JSBin(尽管你真的应该摆脱它)。

如果您使用的是 AngularJs 1.3+,则可以在指令定义对象中使用 'controllerAs'。然后创建一个控制器来做popModal。