为了账号安全,请及时绑定邮箱和手机立即绑定

[Angular1]为什么只输出了最后一个Superman标签的数据?

按照大漠老师2-10的课程做的,不知道为什么三个superman都只能输出["Strength"]

JS部分

var myModule = angular.module('myModule', []);
myModule.directive('superman', function () {
    return {
        $scope: {},
        restrict: 'AE',
        controller: function ($scope) {
            $scope.abilities = [];
            this.addStrength = function () {
                $scope.abilities.push('Strength');
            };
            this.addSpeed = function () {
                $scope.abilities.push('Speed');
            };
            this.addLight = function () {
                $scope.abilities.push('Light');
            };
        },
        link: function ($scope, element, attrs) {
            element.bind('mouseenter', function () {
                console.log($scope.abilities);
            })
        }
    }
})
myModule.directive('strength', function () {
    return{
        require: 'superman',
        link: function ($scope, element, attrs, supermanCtrl) {
            supermanCtrl.addStrength();
        }
    }
})
myModule.directive('speed', function () {
    return{
        require: 'superman',
        link: function ($scope, element, attrs, supermanCtrl) {
            supermanCtrl.addSpeed();
        }
    }
})
myModule.directive('light', function () {
    return{
        require: 'superman',
        link: function ($scope, element, attrs, supermanCtrl) {
            supermanCtrl.addLight();
        }
    }
})

HTML部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="http://cdn.bootcss.com/angular.js/1.6.3/angular.min.js"></script>
    <script src="http://cdn.bootcss.com/angular.js/1.6.3/angular-route.min.js"></script>
    <script src="http://cdn.bootcss.com/angular.js/1.6.3/angular-animate.min.js"></script>
    <script src="js/superman.js"></script>
</head>
<body ng-app="myModule">
    <div>
        <superman strength speed light>1</superman>
    </div>
    <br>
    <div>
        <superman strength speed>2</superman>
    </div>
    <br>
    <div>
        <superman strength>3</superman>
    </div>
</body>
</html>

我尝试把HTML中最后一个Superman修改,发现每次后台也就只能打印出最后一个的数据

正在回答

2 回答

哦哦是作用域的问题,我把scope:{} 写成了 $scope:{}

0 回复 有任何疑惑可以回复我~

哦哦,不是$scope:{} 

而是 scope:{}

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
AngularJS实战
  • 参与学习       205513    人
  • 解答问题       1158    个

一起学习AngularJS的基础教程,通过实例学习并学会AngularJS

进入课程

[Angular1]为什么只输出了最后一个Superman标签的数据?

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信