今天学习指令,遇到了一些困惑:
<!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/scope2.js'></script>
</head>
<body>
<div ng-init = 'someProperty="some date"'>
<div ng-init='siblingProperty="moredata"'>
Inside Div Two : {{aThirdProperty}}
<div ng-init="aThirdProperty='data for 3rd property'" ng-controller="someCtrl">
Inside Div Three: {{aThirdProperty}}
<div ng-controller="secondCtrl">
Inside Div Four: {{aThirdProperty}}
<br>
OutSide myDirective: {{myProperty}}
<div my-directive ng-init="myProperty='wow! that is cool'">
Inside myDirective : {{myProperty}}
</div>
</div>
</div>
</div>
</div>
</body>
</html>
js
var app = angular.module('app', []);
app.controller('someCtrl', ['$scope', function($scope){
}])
app.controller('secondCtrl', ['$scope', function($scope){
console.log($scope.myProperty) //undefined
}])
app.directive('myDirective',function(){
return {
restrict :'A',
scope:false
}
})
为什么打印出来的是undefined?
然后把js指令里的scope改为scope:{}
;为什么弹出来的是这个?就是说为什么外面的OutSide myDirective: wow! that is cool
会有值?
Inside Div Two :
Inside Div Three: data for 3rd property
Inside Div Four: data for 3rd property
OutSide myDirective: wow! that is cool
Inside myDirective : wow! that is cool
首先,你写的这个跟指令没多大关系。指令的
scope
是影响它的template
的作用域,这里并不是。这里undefined的原因是因为controller在ng-init之前执行了。可以用用延时或者
$watch
监听