Passing variable from controller scope to directive

核能气质少年 提交于 2019-12-19 13:10:19

问题


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

{
    name: 'Peter',
    phone: 601002003
}

I've created a directive:

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

and my HTML looks like this:

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

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.


回答1:


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>

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



来源:https://stackoverflow.com/questions/17612977/passing-variable-from-controller-scope-to-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!