AngularJS - 输入变化时,如何在指令中传递值

5

我是一个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: ' + ???);
            });
        }
    };
});
3个回答

5

4

因为您的指令没有创建新的作用域,所以指令中链接方法内的scope变量指向包含两个输入的外部作用域。 因此,您可以将以下内容替换为:

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

使用

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

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

这里是一个有效的 fiddle


编辑:如果您需要在指令中使用隔离作用域,可以在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

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);
});

我在我的fiddle中添加了另一个例子,test3test4


哦,我没想到那会起作用。然而,指令只能注意到第一个文本字段的更改。第二个文本字段如何导致$watch被调用? - Aaron
你只需要在 test2 上添加另一个观察器即可。我已经更新了 fiddle 来展示这一点。 - Dan
我明白了。我刚刚更新了我的代码,现在它可以工作了!不过还有一个问题,如果有超过两个的输入,比如说test3,那该怎么办呢? - Aaron
然后你只需为该输入添加另一个监听器。 我已经更新了 fiddle,请看一下。 - Dan

0

AngularJs指令允许您以不同的方式使用作用域并执行许多需要的很酷的操作。您可以将您的作用域用作非继承、继承和隔离。如果您将作用域用作隔离,则可以传递变量并在任何地方进行绑定。

这里有两篇带有示例的很棒文章,可以帮助您。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接