2014-12-09 55 views
0

我有我的主视图,主页,链接到另一个视图,下载。 我的家庭观点上有两个按钮,“免费试用”和“下载”,它们都指向下载视图,但我希望下载视图的第一段由区分两个按钮的参数决定。基于路由参数的AngularJS页面内容(相同视图)

我该如何去做到这一点?我想也许使用两个控制器,但我是AngularJS的新手,并想知道是否有更好的方法。

回答

0

假设我理解正确的话,你...

有可能在理论上具有由同一个控制器管理两个页面,但不是最好的做法,如果他们有2个独立的观点,在任何情况下,控制器被认为是短暂的。在控制器之间传递数据的“角度方式”是服务。所以,你会做这样的事情:


app.factory('DownloadType',function() { 
    return { 
     type:"free" 
    }; 
    // just used "free" as a default 
}) 
.controller('Home',function($scope,DownloadType) { 
    $scope.setType = function(type) { 
     DownloadType.type = type; 
    }; 
}) 
.controller('Download',function($scope,DownloadType) { 
    $scope.type = DownloadType.type; 
}) 
; 

然后你家的模板可能看起来像:

<button ng-click="setType('free')">Free</button> 
<button ng-click="setType('paid')">Paid</button> 

和你下载的模板

<div ng-show="type === 'free'">This is a free download</div> 
<div ng-show="type === 'paid'">You are paying us! We love you!</div> 

有有些更清洁的方式,例如如果你想要一个点击进入该页面,并设置它:


.controller('Home',function($scope,$location,DownloadType) { 
    $scope.setType = function(type) { 
     DownloadType.type = type; 
     $location.path('/download'); 
    }; 
}) 

最后,如果你想让他们在一个单一的视图,那么你并不需要的服务在所有的,因为你有一个单一视图只有一个控制器。

+0

什么如果我想用单个控制器做到这一点?我对AngularJS很新。如何使用相同的控制器在视图之间传输DownloadType的值?每当我转到下载视图,主控制器重置... – Tsury 2014-12-11 12:40:25

+0

你可以,但你为什么?意识到这意味着范围内的所有内容都将在视图之间共享,并且事情可能会发生。如果你想要,并且接受它是一个单一的视图,那么你可以。 – deitch 2014-12-11 12:46:17

0

您的需求可以通过使用ui-router使用嵌套视图来完成。示例代码,

$stateProvider 
.state('home', { 
    url: "/", 
    templateUrl: "templates/home.html" 
}) 
    .state('product', { 
     url: "/product", 
    templateUrl: "templates/product.html" 
    }) 
.state('product.trial', { 
    url: "/product/trial", 
    templateUrl: "templates/product.trial.html" 
}) 
.state('product.download', { 
    url: "/product/download", 
    templateUrl: "templates/product.download.html" 
}) 

现在product.trial.html & product.download.html里面,把你的第一款只&在product.html,将此代码::::

//the code snippet that is common for all views.... 
<div ui-view>