【发布时间】:2014-01-19 16:06:13
【问题描述】:
我有以下 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 时,单击按钮时,视图 1 标题更改为视图 2 标题,因此我的路由和 GetView2() 函数调用正在工作。但是我的<my-directive> 没有用我在templateUrl 的指令中调用的View2.html 进行更新。
我是 AngularJS 的新手,并尝试将 ng-view 和指令用于多视图类型的场景。我读过我应该避免嵌套视图,并实现指令,但我不知道如何实现这样一个简单的场景。
我可以使用 jQuery 轻松地用 id="two" 替换 Div 的内容,但我正在尝试以适当的 angularjs 方式进行。
【问题讨论】:
-
请发布指令
my-directive代码 -
@MaximShoustin my-directive 代码也出现在上述代码中。我实际上已经发布了整个代码。
-
@Pawan 您正在控制器的范围方法中定义您的指令。这是完全错误的,它不会起作用。
-
@Stewie 是的,我知道它错了......但我无法找到关于如何实现这一目标的正确答案。
标签: javascript angularjs