Angular:如何在指令

时间:2016-09-25 12:11:48

标签: angularjs

.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
            scope.vm.somethingInMyController // vm is undefined
        }
    };
}])

如何在我的指令中同时实现phoneTypevm变量?

1 个答案:

答案 0 :(得分:1)

由于您希望指示具有隔离范围,因此只应通过其属性将所需数据传递到指令scope属性。从指令访问父(使用$ parent)作用域将使其与父作用域紧密结合,假设有一些命名约定。

<强>标记

<div phone-type 
   phone-number="vm.myPhoneNumber" 
   something-more="vm.somethingInMyController">
</div>

<强>指令

scope: {
   phoneNumber: '=phoneType',
   somethingMore: '=' //pass more data here
}