<!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)
}])
Why does it report an error saying that foo
is undefined
?
In addition, the following code also puzzles me:
<!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>'
}
})
Why is there only one result to Google but no text in the h1 tag?
仅有的幸福2017-05-15 17:00:37
The first one: console.log(foo)
This should be console.log($scope.foo)
The second one: Understand the meaning of the replace:true attribute
仅有的幸福2017-05-15 17:00:37
Why do I get an error saying that foo is undefined?
Because your ng-init is defined outside ng-controller="myCtrl". I guess ng-init will not be executed until all controllers are initialized, so foo is undefined at this time
Why is there only one to Google result but no text in the h1 tag?
This question is not clear.