angular.js - angular作用域
PHP中文网
PHP中文网 2017-05-15 16:58:35
[AngularJS讨论组]

今天学习指令,遇到了一些困惑:

    


    
    
    
    

    
    



    
    

Inside p Two : {{aThirdProperty}}

Inside p Three: {{aThirdProperty}}

Inside p Four: {{aThirdProperty}}
OutSide myDirective: {{myProperty}}

Inside myDirective : {{myProperty}}

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
PHP中文网
PHP中文网

认证0级讲师

全部回复(3)
过去多啦不再A梦
<p my-directive ng-init="myProperty='wow! that is cool'">
    Inside myDirective : {{myProperty}}
</p>

首先,你写的这个跟指令没多大关系。指令的scope是影响它的template的作用域,这里并不是。

app.controller('secondCtrl', ['$scope', function($scope){
    console.log($scope.myProperty)    //undefined
}])

这里undefined的原因是因为controller在ng-init之前执行了。可以用用延时或者$watch监听

$timeout(function() {
  console.log($scope.myProperty)
});
// or
$scope.$watch('myProperty', function(newVal) {
  console.log($scope.myProperty)
})
阿神

嗯,,,上面那个undefined我懂了,,不过后面那个我还是有点疑惑,,就是说当scope:{}时,Inside myDirective : {{myProperty}}这个表达式还是属于外面那个作用域是不是?而此时template里面并没有设定,,,所以隔离作用域就没有起作用,我这样理解对吗?
还有一个问题,既然这样,,,那为什么如果把scope设定为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

能否再指点一下,,,谢谢~~

PHP中文网

scope true就是独立隔离的作用域
{}的话只有{}内部有的属性会被隔离开来

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号