角度指令控制器范围可见性

时间:2015-04-23 11:09:43

标签: angularjs angularjs-directive angularjs-scope

问题

为什么模板看不到monkeyselected

普拉克

http://plnkr.co/edit/djS0KWyfJNKD0tfZ0IiV?p=preview

代码

<head>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script>
    <script type="text/javascript">
        angular
            .module('toruSelect', [])
            .directive('toruSelect', function () {
                return {
                    restrict: 'AE', // Allow usage as A - attribute, E - element
                    scope: { // Isolated scope
                        selected: '=' // Bi-directional binding to selected attribute,
                    },
                    controller: ['$scope', function ($scope) {
                        $scope.monkey = 'MONKEY';
                        console.log('toruSelect.controller.$scope', $scope);
                    }]
                }
            });


        var app = angular.module('app', ['toruSelect']);
        app.controller('AppCtrl', function($scope) {
          $scope.val = 'initial';
          $scope.appData = 'App data';
        });
    </script>
</head>
<body ng-controller="AppCtrl">
    <h1>Directives and scopes..</h1>
    <div toru-select selected="val">
        <div style="color: red">RESULT: toruSelect.controller.monkey: {{monkey}}</div>
        <div>EXPECTED: toruSelect.controller.monkey: MONKEY</div>
        <div style="color: red">RESULT: toruSelect.controller.selected: {{selected}}</div>
        <div>EXPECTED: toruSelect.controller.selected: initial</div>
    </div>
</body>

结果

 Directives and scopes..

 RESULT: toruSelect.controller.monkey:
 EXPECTED: toruSelect.controller.monkey: MONKEY
 RESULT: toruSelect.controller.selected:
 EXPECTED: toruSelect.controller.selected: initial

1 个答案:

答案 0 :(得分:1)

正如您在指令的注释中指出的那样,它具有一个独立的范围,因此使用monkey键附加的值在指令范围内可用,而不是在控制器1上。

对于selected,您必须显示{{val}}而不是{{selected}},因为它是指令范围上的双向绑定所关注的变量。