angular.js - angular指令中的scope属性中用&获取父作用域函数的问题
ringa_lee
ringa_lee 2017-05-15 17:07:51
0
1
538

请问为什么alert中最后弹出的数据是父作用域的

点击执行子域的say方法的结果

代码如下:

<p ng-app="myModule">
    <h3>请分别修改父、子作用域表单里的值</h3>
    <p ng-controller="myController">
        父作用域:<br/>
        <input type="text" ng-model="name" /><br/>
        <input type="text" ng-model="sex" /><br/>
        <input type="button" ng-click="say()" value="点击执行父域的say方法" /><br/>
        子作用域:<br/>
        <my-directive my-name="{{name}}" my-sex="sex" get-name='say()'></my-directive><br/>
    </p>

</p>
<script src="../angular-1.5.8/angular.js"></script>
<script type="text/javascript">
    var myModule = angular.module("myModule", []);
    myModule.controller("myController", ['$scope', function($scope){
        $scope.name = "wangmeijian";
        $scope.sex = "boy";
        $scope.say = function(){
            alert( $scope.name +" is a"+ $scope.sex )
        }
    }])
    myModule.directive("myDirective", function(){
        return {
            restrict: "EA",
            scope: {
                myName: "@",
                mySex: "=",
                getName: "&"
            },
            template: "<input type='text' ng-model='myName' /><br/>"+
            "<input type='text' ng-model='mySex' /><br/>"+
            "<input type='button' ng-click='getName()' value='点击执行子域的say方法' />",
        }
    })

</script>
ringa_lee
ringa_lee

ringa_lee

Antworte allen(1)
黄舟

首先一点say打印的是name,和sex。然后你子作用域里是myName和mySex。
还有say中打印的是当前环境下的name和sex,这里有个闭包的概念,举个例子

var fn ;

function test1() {
    var t = 1;
    fn = function(){
        console.log(t);
    }
}
function test2() {
    var t = 2;
    fn();
}
test1();
test2();  //打印的是 1
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage