我有以下HTML:
<!DOCTYPE html>
<html>
<head>
<title>AngularJS Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body ng-app="myApp">
<div class="container">
<div ng-view=""></div>
</div>
<!--Core JS Libraries-->
<script src="js/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/angular-route.min.js"></script>
<!--Core UI Library-->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
//Define an angular module for our app
var myApp = angular.module('myApp', ['ngRoute']);
//Define Routing for app
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'pages/View1.html',
controller: 'HomeController'
}).
when('/design', {
templateUrl: 'pages/2.html',
controller: 'DesignController'
}).
otherwise({
redirectTo: '/home'
});
}]);
var controllers = {};
controllers.HomeController = function ($scope) {
$scope.GetView2 = function ($scope) {
$('#one').hide();
$('#two').show();
myApp.directive('myDirective', function () {
return {
restrict: 'E',
templateUrl: 'pages/view2.html'
}
});
};
};
controllers.DesignController = function ($scope) {
};
//adding the controllers to myApp angularjs app
myApp.controller(controllers);
</script>
</body>
</html>
我的View1.html:
<button ng-click="GetView2()">Get View 2</button>
<br />
<div class="row" id="one">
<h1>View 1</h1>
</div>
<div class="row" id="two" style="display: none;">
<h1>View 2</h1>
<!--change the display to block and load partial here on above button click-->
<my-directive></my-directive>
</div>
和View2.html:
<h3>Something in View2</h3>
现在,当我运行HTML时,在Button上单击,View 1标题chanegs到View 2标题,所以我的路由和GetView2()函数调用正在运行。但是我的<my-directive>
没有使用我在调用templateUrl中的指令中调用的View2.html进行更新。
我是AngularJS的新手,并尝试将ng-view和指令用于多种视图类型的场景。我已经读过我应该避免嵌套视图,并实现指令,但我没有得到如何实现这样一个简单的场景。
我可以轻松地将id的内容替换为id =&#34; 2&#34;使用jQuery,但我试图以适当的angularjs方式做到这一点。
答案 0 :(得分:2)
有更好的方法可以实现您的目标。
首先这个
$('#one').hide();
$('#two').show();
应该避免,因为这是来自Controller的直接DOM操作。
您应该使用或ng-show
指令来隐藏元素。
<div class="row" id="one" ng-show="currentView='one'">
<h1>View 1</h1>
</div>
<div class="row" id="two" ng-show="currentView='two'">
</div>
控制器应该是
$scope.GetView2 = function ($scope) {
$scope.currentView='two';
}
对于您创建的指令,可以由ng-include
完成,例如
<ng-include src='pages/view2.html' />
并确保此路径有一个视图。