angular.js - Problem with using & in the scope attribute in the angular directive to obtain the parent scope function
ringa_lee
ringa_lee 2017-05-15 17:07:51
0
1
542

Excuse me why the last data that pops up in the alert is from the parent scope

The result of clicking to execute the say method of the subdomain

The code is as follows:

<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

reply all(1)
黄舟

First of all, what prints out is name and sex. Then there are myName and mySex in your subscope.
Also, what is printed in say is the name and sex in the current environment. There is a concept of closure here, here is an example

var fn ;

function test1() {
    var t = 1;
    fn = function(){
        console.log(t);
    }
}
function test2() {
    var t = 2;
    fn();
}
test1();
test2();  //打印的是 1
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template