初学者问题:我需要创建一个依赖于控制器变量的html元素。 我在控制器上获得了一些JSON数据,现在我想创建视图。 在json我可以
{ "text": "England", }要么
{ "text": "England", "url": "http://england.com/" }问题出在这里:如果没有提供网址,我想创建一个跨度,否则就是一个链接(a)。 可以在不创建两个元素并使用ng-show或ng-hide的情况下执行此操作吗?
Beginner question: I need to create an html element that depends on a controller variable. I get some data as JSON on controller and now I want to create the view. On json I can have
{ "text": "England", }or
{ "text": "England", "url": "http://england.com/" }Here comes the question: I want to create a span if no url provided, else a link (a). Is possible to do this without creating both elements and using ng-show or ng-hide?
最满意答案
您可以通过几种不同的方式来处理它。 显示隐藏可以工作,你也可以使用ng-if如下:
<span ng-if="url == null"></span> <a ng-if="url != null" href="url"></a>ng-if如果失败则不会在DOM中呈现对象,这与hide / show不同,后者将在DOM中拥有对象但使用样式来显示和隐藏它。
你也可以只有一个点击它的跨度。 如果没有网址,点击可能只返回任何内容。
<span ng-click="myFunction(url)"></span> $scope.myFunction = function(url){ if(!url){ return null; } else{ window.location.href = url; } }There are a few different ways you could handle it. Show hide would work, you could also use ng-if like so:
<span ng-if="url == null"></span> <a ng-if="url != null" href="url"></a>ng-if won't render the object in the DOM if it fails, unlike hide/show which will have the object in the DOM but use styles to show and hide it.
You could also just have a span that has an ng-click on it. The click could just return nothing if there is no url.
<span ng-click="myFunction(url)"></span> $scope.myFunction = function(url){ if(!url){ return null; } else{ window.location.href = url; } }更多推荐
发布评论