angular.js - ng-init与controller
为情所困
为情所困 2017-05-15 16:58:37
0
2
625
<!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)
    
}])

为什么会报错,说fooundefined?
另外下面这段代码也让我不解:

<!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标签里的文字?

为情所困
为情所困

Antworte allen(2)
仅有的幸福

第一个:console.log(foo)
此处应该是console.log($scope.foo)
第二个:理解replace:true属性的含义

仅有的幸福

为什么会报错,说foo是undefined?

因为你的ng-init定义在ng-controller="myCtrl"之外了。我猜所有的controller初始化完了才会执行ng-init,所以此时foo是undefined

为什么结果只有一个to Google而没有h1标签里的文字?

这一问就不清楚了。

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage