将变量从控制器范围传递到指令

aci*_*cid 12 javascript angularjs angularjs-directive angularjs-scope

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

{
    name: 'Peter',
    phone: 601002003
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个指令:

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

我的HTML看起来像这样:

<span phone-type="worker.phone"></span>
Run Code Online (Sandbox Code Playgroud)

如何worker.phone从控制器作用域传递(在此示例中为601002003)指令,以便在link方法中创建逻辑?attrs.phoneType现在显示我的worker.phone字符串.

blu*_*ajo 26

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

.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
        }
    };
}])
Run Code Online (Sandbox Code Playgroud)

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

<span phone-type="worker.phone"></span>
Run Code Online (Sandbox Code Playgroud)

顺便说一句,您不需要限制A.这是默认行为.