AngularJS - 输入更改传递给指令的指令值

Aar*_*AAA 5 angularjs angularjs-directive

我是Angular的初学者,我无法弄清楚如何从指令外部检索数据.我有各种输入正在更新,我需要指令来获取这些数据并使用它.例如,在下面的代码中,第一个输入字段连接到指令并且工作正常,但是没有将指令属性放在第二个输入字段上,如何在指令中更新该字段中输入的数据?

HTML:

<div ng-app="myDirective">
    <input type="text" ng-model="test1" my-directive>
    <input type="text" ng-model="test2">
</div>
Run Code Online (Sandbox Code Playgroud)

指示:

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngModel, function (v) {
                console.log('New Value from field 1: ' + v);
                //console.log('New Value from field 2: ' + ???);
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

Art*_*dod 5

我本来可以在文字中解释过,但我认为如果你看约翰林德奎斯特的 3个视频会好得多:

总结.

它们非常短(每个约4分钟),但非常简单实用.

PS:顺便说一句,我建议你也要看别人.它们都简短而精确,深受喜爱.


Dan*_*Dan 4

由于您的指令不会创建新的作用域,因此scope指令的 link 方法内的变量指向包含两个输入的外部作用域。所以你可以替换:

//console.log('New Value from field 2: ' + ???);
Run Code Online (Sandbox Code Playgroud)

console.log('New Value from field 2: ' + scope.test2);
Run Code Online (Sandbox Code Playgroud)

测试时请确保在第二个输入中输入一些数据,否则它将打印undefined

这是一个工作fiddle


编辑:如果您确实需要在指令中使用隔离范围,您可以在 HTML 中执行以下操作:

<input type="text" ng-model="test1" my-directive="test2">
<input type="text" ng-model="test2">
Run Code Online (Sandbox Code Playgroud)

这里的区别在于现在将test2模型传递到指令中,并通过添加属性在指令中设置与其的绑定scope

scope: {
    otherInput: '=myDirective'
    // this tells the directive to bind the local variable `otherInput`
    // to whatever the `my-directive` attribute value is. In this case, `test2`
},
Run Code Online (Sandbox Code Playgroud)

这允许您访问指令中传递的值。然后你可以$watch按如下方式更改你的 es :

scope.$watch(attrs.ngModel, function (v) {
    console.log('New Value from field 1: ' + v);
    console.log('New Value from field 2: ' + scope.otherInput);
});

// notice the syntax for watching a scope variable
scope.$watch('otherInput', function (v) {
    console.log('New Value from field 1: ' + scope.test1);
    console.log('New Value from field 2: ' + v);
});
Run Code Online (Sandbox Code Playgroud)

我已将其作为另一个示例包含在我的小提琴中,test3并且test4.