angular.js - ng-init与controller

浏览:37日期:2023-01-20

问题描述

<!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='https://www.6hehe.com/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='https://www.6hehe.com/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标签里的文字?

问题解答

回答1:

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

回答2:

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

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

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

这一问就不清楚了。

相关文章: