Angular show / hide static html?

时间:2014-04-17 18:57:44

标签: javascript html angularjs

我有一个网站,我希望能够显示服务。已经有格式良好的html代码来描述每个服务,我想使用已经制作的代码。

我只希望一次显示一个服务的描述(我已经将其表示为默认)。当您单击服务类别时,它应隐藏所有其他描述,然后仅显示指定的html元素。

我想我完全是在思考这个问题,而且确实有一种简单的方法可以做到这一点。

我不想做的是将设计师所使用的所有html代码放入范围。这意味着必须制作一个html代码的javascript字符串,这很难看。

我正在尝试做任何事情......

$scope.services =   [{  
            "id":"music",
            "label":"Music",
            "show":false
        },
        ...
        ];
$scope.showElement = function(service){
    $scope.hideAll(); //sets all services "show" var to "false"
    return service.show = true;
};

$scope.getServiceByElementId = function(id){
    for (var i=0; i<$scope.services.length; i++){
        var service = $scope.services[i];
        if (id==service.id){
            return service;
        }
    }
};

html部分如下所示:

<span ng-repeat="service in services">
        <span id="{{service.id}}">
            <a href="#" ng-click="showElement(service)">
                {{service.label}}
            </a>
        </span>
        <span ng-show="! $last"> | </span>
    </span>
...end category menu

    <span ng-show="{{getServiceByElementId('music').show}}">
        <p>premade html code that anyone can edit for music</p>
    </span>

    <span ng-show="{{getServiceByElementId('voip').show}}">
        <p>premade html code that anyone can edit for voip</p>
    </span>

    <span ng-show="{{getServiceByElementId('websites').show}}">
        <p>premade html code that anyone can edit for websites info</p>
    </span>

    <span ng-show="{{getServiceByElementId('svn').show}}">
        <p>premade html code that anyone can edit for svn repository info</p>
    </span>

到目前为止,我注意到这对于如此简单的事情来说真的很复杂,所以显然我做的事情非常错误......我错过了什么?我没有很多运气找到任何解释角度如何打开和关闭静态html元素的教程......

http://jsfiddle.net/udQSc/

在知道我正在尝试做什么的时候,如果我走错了路,请告诉我,以便我可以回到正确的路上:)

2 个答案:

答案 0 :(得分:4)

您可以使用ng-switch

简化一些事情
<div ng-switch on="activeService">
    <span ng-switch-when="music">
        <p>premade html code that anyone can edit for music</p>
    </span>

    <span ng-switch-when="voip">
        <p>premade html code that anyone can edit for voip</p>
    </span>

    <span ng-switch-when="websites">
        <p>premade html code that anyone can edit for websites info</p>
    </span>

    <span ng-switch-when="svn">
        <p>premade html code that anyone can edit for svn repository info</p>
    </span>
</div>  

http://jsfiddle.net/robianmcd/7YGUR/

答案 1 :(得分:1)

你可以存储html&#39; chunk&#39;在单独的文件中,使用ng-include导入它们。

例如,如果music中有/templates/music.html的html,svn中有/templates/svn.html的模板等,则可以使用

<ng-include src="'/templates/' + serviceName + '.html'" />

更改scope.serviceName时,模板将更新。