2014-04-01 63 views
0

我有角碼使用'box1'指令創建一個div。那個盒子裏面有一個按鈕。當單擊該按鈕時,我希望它調用另一個稱爲「box2」的指令。這個box2將進入box1。我該怎麼做呢?使用按鈕調用另一個指令內部的指令?

HTML:

<div ng-app="myApp"> 
    <div> 
     <box1> 
     </box1> 
    </div> 
</div> 

ANGULAR:

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

app.directive("box1", function() { 
    return { 
     restrict: "E", 
     template: '<div id="group_1">Content from the first box! <button>Create 2nd Box</button></div>' 
    } 
}); 

app.directive("box2", function() { 
    return { 
     restrict: "E", 
     template: '<div id="group_1_1"> Content from second box! </div>', 
    } 
}); 

什麼是角的正確方法,使在第一個框中的按鈕來調用BOX2指令。此外,我不能只寫box1指令模板,因爲它只會自動生成box2。我不想那樣。我希望他們點擊box1的按鈕來製作box2。

鏈接到JsFiddle,如果任何人有興趣。 http://jsfiddle.net/RZSKe/

+0

到底是什麼「調用BOX2指令」是什麼意思?要呈現box2指令? –

+0

Box1指令是我想在box1模板內按下按鈕時在box1內部填充的內容。所以是渲染box2 – allencoded

+0

看看這是你想要的:http://jsfiddle.net/RZSKe/1/ –

回答

2

不知道我是否正確理解你,但似乎你應該使用$compile服務。下面是我所說的意思種子 - 它應該是可能根據您的需求:

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

app.directive("box1", function ($compile) { 
    return { 
     restrict: "E", 
     template: '<div id="group_1">Content from the first box! <button ng-click="createBox2()">Create 2nd Box</button></div>', 
     link: function (scope, el) { 
      scope.createBox2 = function() { 
       var box2 = $compile("<box2></box2>")(scope); 
       el.append(box2); 
      } 
     } 
    } 
}); 

app.directive("box2", function() { 
    return { 
     restrict: "E", 
     template: '<div id="group_1_1"> Content from second box! </div>', 
    } 
}); 

---DEMO---

相關問題