我有一个有角度的应用with one main view
和two main controllers
我想toggle between
这两个控制器depending on the button click.
这是如何通过angularjs实现的?
完整说明: 我有一个网页,其中包含一些动态文本和图表。我想用英语和德语两种语言。基本上我想要一个控制器改变英文文本,如果语言切换到英语和另一个德语。我试过Angular Translate但是我不知道如何用它来翻译从函数返回的值,所以决定通过控制器来改变它。
我通过ui-router更新页面我的代码
function routerConfig($stateProvider, $urlRouterProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainController',
controllerAs: 'main'
})
.state('line', {
url: '/lineChart',
templateUrl: 'app/simplerChart/simplerChart.html',
controller: 'SimpleChartController'
});
答案 0 :(得分:2)
我们有两条路线,两条控制器绑定到每条路线。您可以在两条路线之间切换:/english
和/german
。两者都有不同的控制器,都有不同的模板。
1)如果您点击“第一次观看”,您将被带到“#/ english”网址,其中您将MainFirstCtrl
绑定到此HTML:
<div style="background: mediumpurple">{{ctrl.title}}</div>
2)如果您点击“第一次观看”,您将被带到“#/ english”网址,其中您将MainSecondCtrl
绑定到此HTML:
<div style="background: yellowgreen">{{ctrl.title}}</div>
3)现在使用ui-sref你可以改变状态:
<button type="button" ui-sref="first">Go to First View (/english)</button>
<button type="button" ui-sref="second">Go to Second View (/german)</button>
4)状态在ui-router配置中定义如下:
$stateProvider.state('first', {
url: '/first',
template: '<div style="background: mediumpurple">{{ctrl.title}}</div>',
controller: 'MainFirstCtrl',
controllerAs: 'ctrl'
});
以下工作示例:
var myapp = angular.module('myapp', ['ui.router']);
//Here are our routes defined
myapp.config(['$stateProvider', function ($stateProvider) {
$stateProvider.state('first', {
url: '/english',
template: '<div class="view" style="background: mediumpurple">{{ctrl.title}}</div>',
controller: 'MainFirstCtrl',
controllerAs: 'ctrl'
});
$stateProvider.state('second', {
url: '/german',
template: '<div class="view" style="background: yellowgreen">{{ctrl.title}}</div>',
controller: 'MainSecondCtrl',
controllerAs: 'ctrl'
});
}]);
//Here are our two different controllers that would control the same view BUT with different routes
myapp.controller('MainFirstCtrl', ['$scope', function($scope) {
this.title = 'This is english view';
}]);
myapp.controller('MainSecondCtrl', ['$scope', function($scope) {
this.title = 'This is german view';
}]);
button {
background: #1e6791;
border: 0;
color: #fff;
padding: 15px 20px;
font-family: arial;
font-size: 15px;
margin: 15px 0px;
box-shadow: 0px 0px 1px rgba(0,0,0,.3);
}
.view {
width:300px;
height:150px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>
</head>
<body ng-app="myapp">
<button type="button" ui-sref="first">Go to First View (/english)</button>
<button type="button" ui-sref="second">Go to Second View (/german)</button>
<div ui-view></div>
<div show-contact></div>
</body>
</html>