2015-03-31 57 views
1

我想了解如何隔離範圍,bindToController和controllerAs工作。沒有模板使用bindToController

如果我就與一個孤立的範圍和模板的指令,它按預期工作:

<!DOCTYPE html> 
<html ng-app="app"> 
<head> 
    <style> 
    </style> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
    <script> 
     function directiveTest() { 
      function CtrlTest() { 
       this.foo = "honk"; 
       this.clearFoo = function() { 
        this.foo=''; 
       }; 
      } 
      return { 
       restrict : 'E', 
       scope: { 
        label : '@', 
        lg : '@' 
       }, 
       bindToController : true, 
       controller: CtrlTest, 
       controllerAs: 'ctrlTest', 
       template: '<label>\n {{ ctrlTest.label }}\n <input type="text" ng-model="ctrlTest.foo"/>\n</label>\n<button ng-click="ctrlTest.clearFoo()">Clear</button>\n\n<div>{{ ctrlTest.foo }}</div>\n\n<div ng-show="ctrlTest.foo.length> ctrlTest.lg">\n Long string !\n</div>\n' 
      }; 
     } 
     var app = angular.module('app',[]); 
     app.directive('dirTest',[directiveTest]); 
    </script> 
</head> 
<body> 
    <dir-test label="Type something now:" lg="7"> 
    </dir-test> 
</body> 
</html> 

我試圖做同樣的沒有模板,但我不能讓它工作:

<!DOCTYPE html> 
<html ng-app="app"> 
<head> 
    <style> 
    </style> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
    <script> 
     function directiveTest() { 
      function CtrlTest() { 
       this.foo = "honk"; 
       this.clearFoo = function() { 
        this.foo=''; 
       }; 
      } 
      return { 
       restrict : 'E', 
       scope: { 
       }, 
       bindToController : true, 
       controller: CtrlTest, 
       controllerAs: 'ctrlTest' 
      }; 
     } 
     var app = angular.module('app',[]); 
     app.directive('dirTest',[directiveTest]); 
    </script> 
</head> 
<body> 
    <dir-test> 
     <label> 
      Type something again : 
      <input type="text" ng-model="ctrlTest.foo"/> 
     </label> 
     <button ng-click="ctrlTest.clearFoo()">Clear</button> 

     <div>{{ ctrlTest.foo }}</div> 

     <div ng-show="ctrlTest.foo.length>7"> 
      Long string ! 
     </div> 
    </dir-test> 
</body> 
</html> 

但是,如果我將範圍設置爲true而不是隔離範圍,則適用。

有人可以向我解釋如何使第二個例子工作,或者如果它不可能,爲什麼?

+1

這是範圍是多麼孤立的工作。 標籤中的內容沒有得到dirTest指令的範圍。只有模板中的內容才能從指令中獲取範圍。任何你不想使用模板的理由? – rob 2015-03-31 14:12:37

+0

我想知道是否有辦法在內容可能稍有變化的情況下制定指令。在這種情況下,制定隔離範圍可能沒有意義。我只是在試驗和學習。 – 2015-04-01 06:33:21

回答