Angular - 切换开/关div

时间:2015-08-11 20:55:08

标签: angularjs

Please see this jsFiddle

在这个小提琴中,我有两个包含广告展示位置的html div。我想使用Angular打开/关闭它们,因此在一个实例Ad 1将显示,而在另一个实例中,Ad 2将显示。请注意,在每个div中我都有Javascript内容,我也想打开/关闭。

我基本上想要更新View。

HTML:

<div ng-controller="MyCntrl">
        <div id = "ad1" class = "ad1">
            AD 1
            <img src ="http://images.dailytech.com/frontpage/fp__Apple-100x100.png"></img>
            <script><!-- code here --></</script>
        </div>

        <div id = "ad2" class = "ad2">
            AD 2
            <img src ="http://fixmypod.ca/image/cache/data/NEWEST_Phones/Samsung_Galaxy_Note_2-100x100.jpg"></img>
            <script><!-- code here --></</script>
        </div>

</div>

角:

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

app.controller('MyCtrl',['$scope','$element', function($scope, $element) {

  $scope.changeView = function(ad){
      //make ad x show and the other ad hidden
   }

}]);

我怎样才能继续这样做?

2 个答案:

答案 0 :(得分:1)

只需使用ng-show而不是类,并在范围内使用布尔属性来触发div。

HTML:

<div ng-controller="MyCntrl">
    <div id="ad1" ng-show="toggle">
        AD 1
        <img src ="http://images.dailytech.com/frontpage/fp__Apple-100x100.png"></img>
        <script><!-- code here --></</script>
    </div>
    <div id="ad2" ng-show="!toggle">
        AD 2
        <img src ="http://fixmypod.ca/image/cache/data/NEWEST_Phones/Samsung_Galaxy_Note_2-100x100.jpg"></img>
        <script><!-- code here --></</script>
    </div>
</div>

角:

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

app.controller('MyCtrl',['$scope','$element', function($scope, $element) {
    $scope.toggle = true;
    $scope.changeView = function(ad){
        $scope.toggle = !$scope.toggle;
    }
}]);

或者,您可以使用ng-include仅基于属性呈现模板。

HTML:

<div ng-controller="MyCntrl">
    <div ng-if="condition">
        <div ng-include="`template/path/ad1`"></div>
    </div>
    <div ng-if="!condition">
        <div ng-include="`template/path/ad2`"></div>
    </div>
</div>

答案 1 :(得分:1)

你可以通过

来完成

<强>控制器

$scope.myDiv=true;

查看

<div ng-show="myDiv">
  if true this will visible
</div>