在嵌套指令中访问父范围变量

时间:2015-11-10 19:34:14

标签: javascript angularjs angularjs-directive angularjs-scope

我在另一个指令中声明了一个指令,它应该使用父作用域中的一个变量。这就是结构的样子:

主控制器:

angular.module('app')
    .controller('MainCtrl', function ($scope, Settings){
$scope.userName = "";
$scope.init = function(){
 Settings.getUser()
                .then(function (res) {
                    $scope.userName = res.data.userName;
                    console.dir(res);
                }).catch(function (err) {
                    //showError(err.data)
                });
};
}

main.html中

<div id="wrapper">

        <!-- Navigation -->

        <header></header>
        <!-- /.navbar-top-links -->


        <!-- /.navbar-static-side -->

            <div id="page-wrapper" style="min-height: 561px;">

                <div ui-view></div>

            </div>
            <!-- /#page-wrapper -->
    </div>

了header.html

<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
<header-notification user-name="{{userName}}"></header-notification>
</nav>

头-notification.js

angular.module('app')
    .directive('headerNotification', function (Settings, $ngBootbox) {
        return {
            templateUrl: 'scripts/directives/header/header-notification/header-notification.html',
            restrict: 'E',
            scope: {
                'userName': '='
            },
            controller: ['$scope', function ($scope) {
                console.log($scope.userName);
            }],
            link: function (scope, element, attrs) {
                console.log(scope.userName);
            }
        }
    });

我无法访问该值,我也尝试了scope.$watch但仍然获得undefined值。

1 个答案:

答案 0 :(得分:1)

您需要进行3项更改

  1. Angular JS对camelcase不是很好。由于某种原因,它不一致地不识别/绑定它们。所以,我会使用“用户名
  2. 传递变量时删除括号。因此,而不是{{username}}只使用username
  3. 变量名称( userName - 请将此更改为“用户名”)您在指令中使用的内容与header.html中的内容不匹配(用户-name

  4. 希望这能解决问题。