2017-03-13 31 views
0

我有一個指令需要與使用隔離範圍的指令一起工作。這當然引起了這個錯誤:在沒有隔離範圍的指令中雙向數據綁定

Multiple directives asking for new/isolated scope 

我的代碼看起來大致是這樣的:

HTML:

<p custom_directive='variable' vendor_directive>Test</p> 

JS:

app.directive('ExampleDirective',function() { 
    return { 
     restrict: 'A', 
     scope: { 
      exampleDirective: '=' 
     }, 
     link: function(scope,element,attributes){ 
      // manipulate scope.exampleDirective 
     } 
    } 

    }); 

我已經嘗試刪除範圍完全從我的指示和沿用以下內容:

scope.exampleDirective = scope.$eval(attributes.exampleDirective) 

但是,這隻能看到對象的工作,而我的目標是其他類型的變量。

這是如何實現的?

+0

使用[$ parse service](https://docs.angularjs.org/api/ng/service/$parse)創建setter和getter函數。 – georgeawg

回答

-1

試試這個:

app.directive('ExampleDirective',function() { 
    return { 
    restrict: 'A', 
    bindToController: { 
     exampleDirective: '=' 
    }, 
    scope: true, 
    link: function(scope,element,attributes) { 
     // manipulate scope.exampleDirective 
    } 
    } 
}); 
+0

該指令的控制器應該如何工作? – ferp

0

試試下面的代碼:

var myApp = angular.module('myApp', []); 
 
myApp.controller('myController', ['$scope', function($scope){ 
 
    
 
}]); 
 

 
myApp.directive('exampleDirective',function() { 
 
    return { 
 
     restrict: 'A', 
 
     scope: { 
 
      data:"=" 
 
     }, 
 
     template: 'In Directive :<div> <input type="text" ng-model="data"></div>', 
 
     link: function(scope,element,attributes){ 
 
      // manipulate scope.exampleDirective 
 
     } 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
In Controller: 
 
<div ng-app="myApp" ng-controller="myController"> 
 
<input type="text" ng-model="ctrlTest"/> 
 
<div example-directive data="ctrlTest"></div> 
 
</div>

0

,我可以在這裏看到的是,vendor_directive有問題已經創造了一個孤立的範圍,使角不允許您在相同的摘要循環中定義另一個獨立的作用域。有兩種方法可以解決這個問題 -

  • 首先也是更復雜的一點是,您裝飾供應商指令以包含自定義指令的功能。這是更穩定和可靠的方式。通過這裏的裝飾decorator

  • 第二和簡單的方法的文檔,走的是使用上attributes.exampleDirective變量$觀察家和執行功能,每次它改變所以它會模仿雙向綁定你的願望

希望這會有所幫助

+0

由於這兩個指令不總是在一起,所以在這種情況下,裝飾器實際上是不可行的,我只需要在它們出現時解決它。至於你的第二個解決方案,我不能$看他們,因爲他們只是字符串而不是綁定在這一點上,他們永遠不會改變。 – ferp

相關問題