<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="../css/lib/bootstrap4.css">
<script type="text/javascript" src='../js/lib/angular.js' ></script>
<script type="text/javascript" src='js/initAndController.js'></script>
</head>
<body ng-init="foo='bar'">
<p ng-controller="myCtrl">
</p>
</body>
</html>
js
var app = angular.module('app', []);
app.controller('myCtrl', ['$scope', function($scope){
console.log(foo)
}])
為什麼會報錯,說foo
是undefined
?
另外下面這段程式碼也讓我不解:
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="../css/lib/bootstrap4.css">
<script type="text/javascript" src='../js/lib/angular.js' ></script>
<script type="text/javascript" src='js/directive.js'></script>
</head>
<body ng-controller="myCtrl">
<my-directive />
<h1 ng-init="greet='hello world'">
The greeting is {{greet}}
</h1>
</body>
</html>
js
var app = angular.module('app', []);
app.controller('myCtrl', ['$scope', function($scope){
}])
app.directive('myDirective',function(){
return {
restrict : 'E',
replace : true,
template : '<a href="http://google.com">to Google</a>'
}
})
為什麼結果只有一個to Google而沒有h1標籤裡的文字?
第一個:console.log(foo)
此處應該是console.log($scope.foo)
第二個:理解replace:true屬性的含義
因為你的ng-init定義在ng-controller="myCtrl"之外了。我猜所有的controller初始化完了才會執行ng-init,所以此時foo是undefined
這一問就不清楚了。