3

我有一個問題,在HTML頁面上顯示和隱藏div模板。這裏是一個簡單的JSFiddle示例ExamplengShow無法從HTML上的模板工作

app.directive('example', function() { 

    return { 
     restrict: 'E', 
     template: '<button ng-click=\"clickMe()\">Click me</button>', 
     scope: { 
      exampleAttr: '@' 
     }, 
     link: function (scope) { 
      scope.clickMe = function() { 
     scope.showMe = !scope.showMe; 
    }; 
     } 
    }; 
}); 

和HTML是這樣的:

<body ng-app="demo" ng-controller="exampleController"> 
<div> 
    <div ng-controller="exampleController as ctrl"> 
     <example example-attr="xxx"> 
      <p ng-show="showMe">Text to show</p> 
     </example> 
    </div> 
</div> 

我不能在這個example添加我的HTML代碼模板一樣,因爲我的div我要顯示或隱藏是一個整個html頁面。

app.directive('example', function() { 

    return { 
     restrict: 'E', 
     template: '<p ng-show=\"showMe\">Text to show</p><button ng-click=\"clickMe()\">Click me</button>', 
     scope: { 
      exampleAttr: '@' 
     }, 
     link: function (scope) { 
      scope.clickMe = function() { 
     scope.showMe = !scope.showMe; 
    }; 
     } 
    }; 
}); 

在此先感謝

回答

3

您需要使用transclusion如果你想在你的<example> <!-- this stuff here --> </example>中有東西,一旦指令被編譯和創建出現。

搭乘指令中的scope: {}對象。

jsFiddle demo

app.directive('example', function() { 
    return { 
     restrict: 'E', 

     template: '<div ng-transclude></div><button ng-click="clickMe()">Click me</button>', 

     //^notice the ng-transclude here, you can place this wherever 
     //you want that HTML to show up 

     // scope : {}, <-- remove this 
     transclude: true, // <--- transclusion 

     // transclude is a "fancy" word for, put those things that are 
     // located inside the directive html inside of the template 
     //at a given location 

     link: function (scope) { 
      /* this remains the same */ 
     } 
    }; 
}); 

這將有它的工作如預期!

旁註:你不需要逃生,因爲 \"您的雙引號,你有一個single quote ' <html here> ' 字符串內您的模板。

+0

感謝男人,它的工作,我想要的 – Ayyoub

+1

並且非常感謝解釋和評論 – Ayyoub

+0

沒問題,很高興幫助@Ayyoub –

2

你可以不喜歡這樣 - Fiddle

JS

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

app.controller('exampleController', function ($scope) { 
    $scope.showMe = false; 
}); 

app.directive('example', function() { 

    return { 
     restrict: 'E', 
     template: '<button ng-click="clickMe()">Click me</button><br>', 
     scope: { 
      exampleAttr: '@', 
      showMe: "=" 
     }, 
     link: function (scope) { 
      scope.clickMe = function() { 
       scope.showMe = !scope.showMe; 
      }; 
     } 
    }; 
}); 

標記

<body ng-app="demo" ng-controller="exampleController"> 
    <div> 
     <div ng-controller="exampleController as ctrl"> 
      <example example-attr="xxx" show-me="showMe"></example> 
      <p ng-show="showMe">Text to show</p> 
     </div> 
    </div> 
</body> 
+0

我mentionned,我不能把它的模板,因爲它實際上是一個完整的HTML頁面,我給剛恩例如:) 但@mcpDESIGNS給出的解決方案是工作 – Ayyoub

+0

@Ayyoub是啊,我看到了。查看更新。很高興你找到了解決方案。我的替代品。 –

+0

是的,我試圖做你喜歡做的事,但我做不到。 我不能投票我沒有足夠的聲譽,我不認爲我可以接受的答案,但你的工作太多,謝謝很多人 – Ayyoub

相關問題