Rumah > Soal Jawab > teks badan
今天学习指令,遇到了一些困惑:
<!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>
<p ng-init = 'someProperty="some date"'>
<p ng-init='siblingProperty="moredata"'>
Inside p Two : {{aThirdProperty}}
<p ng-init="aThirdProperty='data for 3rd property'" ng-controller="someCtrl">
Inside p Three: {{aThirdProperty}}
<p ng-controller="secondCtrl">
Inside p Four: {{aThirdProperty}}
<br>
OutSide myDirective: {{myProperty}}
<p my-directive ng-init="myProperty='wow! that is cool'">
Inside myDirective : {{myProperty}}
</p>
</p>
</p>
</p>
</p>
</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 p Two :
Inside p Three: data for 3rd property
Inside p Four: data for 3rd property
OutSide myDirective: wow! that is cool
Inside myDirective : wow! that is cool
过去多啦不再A梦2017-05-15 17:00:35
<p my-directive ng-init="myProperty='wow! that is cool'">
Inside myDirective : {{myProperty}}
</p>
Pertama sekali, apa yang anda tulis tidak ada kaitan dengan arahan. scope
arahan ialah skop template
yang mempengaruhinya, yang tidak berlaku di sini.
app.controller('secondCtrl', ['$scope', function($scope){
console.log($scope.myProperty) //undefined
}])
Sebab mengapa ia tidak ditentukan di sini adalah kerana pengawal dilaksanakan sebelum ng-init. Anda boleh menggunakan kelewatan atau $watch
pantau
$timeout(function() {
console.log($scope.myProperty)
});
// or
$scope.$watch('myProperty', function(newVal) {
console.log($scope.myProperty)
})
阿神2017-05-15 17:00:35
Hmm, saya faham yang tidak ditakrifkan di atas, tetapi saya masih keliru sedikit tentang yang terakhir, iaitu, apabila scope:{}
, ungkapan Inside myDirective : {{myProperty}}
masih tergolong dalam skop luar, bukan? Pada masa ini, tiada tetapan dalam templat,,, jadi skop pengasingan tidak berfungsi Adakah saya faham ini dengan betul?
Terdapat soalan lain Jika ini berlaku, mengapa keputusan berikut berlaku jika skop ditetapkan kepada scope:true
:
Inside p Two :
Inside p Three: data for 3rd property
Inside p Four: data for 3rd property
OutSide myDirective:
Inside myDirect33ive : wow! that is cool
Bolehkah anda memberi saya nasihat lagi. Terima kasih~~
PHP中文网2017-05-15 17:00:35
Skop benar ialah skop bebas dan terpencil
Jika {}, hanya sifat di dalam {} akan diasingkan