2014-12-30 217 views
0

要開始,我成立了一個的jsfiddle這裏:http://jsfiddle.net/qLagkgt5/3/

我希望標題是明確的,但基本上,我試圖使用指令來幫助重複的HTML。在JSFiddle的例子中,我使用了一個帶有間距和框型選項的box指令。

,我變成重複的代碼生成的HTML:

<div class="box"> 
    <div class="box-inner"> 
     {{CONTENT GOES HERE}} 
    </div> 
</div> 

隨着選修課程:

<div class="box spacing-small box-rounded"> 
    <div class="box-inner"> 
     {{CONTENT GOES HERE}} 
    </div> 
</div> 

我想什麼,能夠做的是:

<box spacing="small" box-type="rounded"> 
    {{CONTENT GOES HERE}} 
</box> 

這是顯然是一組非常簡化的html,不一定需要指令,但它只是一個例子來說明我正在運行什麼。

我們對事物的角度側...

這裏是我的控制器:

app.controller("Ctrl", ["$scope", function($scope) { 

    $scope.text = "Starting Text... FOOBAR!"; 

}]); 

這裏是我的指令:

app.directive("box", function() { 
    return { 
     restrict: "E", 
     transclude: true, 
     replace: true, 
     scope: { 
      spacing: "@", 
      boxType: "@" 
     }, 
     template: '<div class="box" ng-class="{\'spacing-{{spacing}}\' : spacing, \'box-{{boxType}}\' : boxType}"> <div class="box-inner" ng-transclude></div></div>' 
    } 
}); 

如果我現在把我的指令放在html裏面,像這樣的控制器:

<div class="wrap" ng-controller="controller"> 
    {{text}} 
    <box spacing="small"> 
     <input ng-model="text"/> 
    </box> 
</div> 

的$ scope.text那就是<box>外面當我改變箱內輸入永遠不會更新。

  1. 如何使它在使用此指令時,框內的內容上升到父範圍而不是隔離範圍?
  2. 如果我在另一個框中嵌套一個框,我是否也可以將它放到同一個父範圍內?

謝謝!

回答

0

我在閱讀您的文章時立即在我的腦海中跳起來看到了一些關於stackoverflow的信息。它說「如果你做得沒有點,你做錯了......」我會搜索文章,並在發現它後立即發佈它,但現在我想我「修復」你的代碼:

<div ng-app="app" ng-controller="Ctrl"> 
    <h1><span class="grey">$scope.data.text:</span> {{data.text}}</h1> 
    <box spacing="large" box-type="rounded"> 
     <h2><span class="grey">$scope.text in box directive:</span> {{data.text}}</h2> 
     <input ng-model="data.text" /> 
    </box> 
    <box spacing="small" box-type="rounded-shadow"> 
     <h2><span class="grey">$scope.text in different box directive:</span> {{data.text}}</h2> 
     <input ng-model="data.text" /> 
    </box> 
</div> 

var app = angular.module("app", []); 

app.controller("Ctrl", ["$scope", function($scope) { 

    $scope.data = {}; 
    $scope.data.text = "Starting Text... FOOBAR!"; 

}]); 

app.directive("box", function() { 
    return { 
     restrict: "E", 
     transclude: true, 
     replace: true, 
     scope: { 
      spacing: "@", 
      boxType: "@" 
     }, 
     template: '<div class="box" ng-class="{\'spacing-{{spacing}}\' : spacing, \'box-{{boxType}}\' : boxType}"> <div class="box-inner" ng-transclude></div></div>' 
    } 
}); 

您必須創建一個對象並將其用於數據綁定。我現在使用「data.text」並用這個表達式進行綁定。

乾杯, Tim。

P.S .:有很多鏈接。

要提只有兩種:

AngularJS: If you are not using a .(dot) in your models you are doing it wrong?

AngularJS: dot in ng-model