繁体   English   中英

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

[英]AngularJS - Input change outside directive value passed in to directive

我是 AngularJs 的初学者,我无法弄清楚如何从指令外部检索数据。 我有各种输入正在更新,我需要指令来获取这些数据并使用它。

例如,在下面的代码中,第一个输入字段连接到指令并且工作正常,但是没有将指令属性放在第二个输入字段上,如何在指令中更新该字段中键入的数据?

HTML:

<div ng-app="myDirective">
    <input type="text" ng-model="test1" my-directive>
    <input type="text" ng-model="test2">
</div>

指示:

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: ' + ???);
            });
        }
    };
});

我本可以用文字解释这一点,但我认为如果您观看john lindquist 的这 3 个视频会更好:

总结

它们真的很短(每个约 4 分钟),但非常简单和有用。

PS:顺便说一句,我建议你也看别人。 他们都简短而准确,喜欢他们。

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

//console.log('New Value from field 2: ' + ???);

console.log('New Value from field 2: ' + scope.test2);

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

这是一个工作小提琴


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

<input type="text" ng-model="test1" my-directive="test2">
<input type="text" ng-model="test2">

这里的区别现在是将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`
},

这允许您访问指令中传递的值。 然后你将改变你的$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);
});

我已经把它作为另一个例子包含在我的小提琴中, test3test4

AngularJs 指令允许你以不同的方式使用作用域并做许多你需要的很酷的事情。你可以使用你的作用域不继承、继承和隔离。如果你使用隔离的作用域,你可以传递变量并将其绑定到任何你想要的地方。

这里有 2 篇带有示例的很酷的文章,可以帮助您

http://www.w3docs.com/snippets/angularjs/change-variable-from-outside-of-directive.html

http://www.w3docs.com/snippets/angularjs/bind-variable-inside-angularjs-directive-isolated-scope.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM