将变量从控制器范围传递到指令 [英] Passing variable from controller scope to directive

查看:60
本文介绍了将变量从控制器范围传递到指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我定义了 $ scope.worker 这是一个普通的JS对象:

In my controller I've defined $scope.worker which is a plain JS object:

{
    name: 'Peter',
    phone: 601002003
}

我创建了一个指令:

.directive('phoneType', [function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            console.log(attrs);
        }
    };
}])

我的HTML如下所示:

and my HTML looks like this:

<span phone-type="worker.phone"></span>

如何传递 worker.phone (在这个例子中601002003)从控制器范围到指令,所以我可以在链接方法中创建我的逻辑? attrs.phoneType 现在显示 worker.phone string。

How do I pass worker.phone (in this example 601002003) from the controller scope to the directive, so I can create my logic in the link method? attrs.phoneType right now shows me worker.phone string.

推荐答案

您也可以通过双向绑定将值传递给指令:

You could also pass the value to the directive via two way binding:

.directive('phoneType', [function () {
    return {
        scope: {
          phoneNumber: '=phoneType'
        }
        link: function (scope, element, attrs) {
            // now do stuff with the number, you can access it through the scope
            scope.phoneNumber // contains the number
        }
    };
}])

现在您可以直接通过隔离范围访问该号码。
模板看起来像这样:

Now you can access the number directly through the isolate scope. Template would look like this:

<span phone-type="worker.phone"></span>

顺便说一下,你不需要限制A.这是默认行为。

By the way, you don't need the restrict A. This is the default behavior.

这篇关于将变量从控制器范围传递到指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆