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

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

问题描述

在我的控制器中,我定义了 $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)从控制器范围传递到指令,以便我可以在 link 方法中创建我的逻辑?attrs.phoneType 现在向我显示 worker.phone 字符串.

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天全站免登陆