在 angular 指令 link 中使用数据?

Use data in angular directive link?

我如何使用从控制器传递到标签属性指令的数据??它在控制台中显示未定义。

App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
       restrict: 'E',
       scope: {
           gamesList: '=',
       }.
       link: function(scope,attrs){
           console.log(scope.gamesList); //undefined
       }
    }
}])

和html:

<applist games-List="games">
    <div ng-repeat="(key, value) in gamesList | groupBy: 'game.id'"> ... </div>
</applist>

您必须将标签更改为:

<applist games-list="games">...</applist>

此外,在 angular 中,属性中的驼峰式大小写与 html 标记中的“-”一起使用。你忘记了 's' 到 'game'

编辑:如前所述,link 之前的点使指令中断。尝试:

return {
   restrict: 'E',
   scope: {
       gamesList: '='
   }, //change dot to coma
   link: function(scope,attrs){
       console.log(scope.gamesList); //undefined
   }
}

使用@获取字符串值: 修改代码:

<!DOCTYPE html>
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<applist games-list="games"></applist>
<script>
var App=angular.module('myApp',[]);

App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
       restrict: 'E',
       transclude:true,
       scope: {
           gamesList: '@',
       },
       link: function(scope,attrs){
           console.log(scope.gamesList); //games
       }
    }
}])
</script>


</body>
</html>

要从指令属性中获取数据,您可以使用以下代码

console.log(scope.gamesList);

您的指令将是

App.directive('applist', ['$rootScope', function($rootScope) {
'use strict';
    return {
        restrict: 'E',
       scope: {
           gamesList: '@',
       },
       link: function(scope,attrs){
           console.log(scope.gamesList); //games
       }
    }
}])