繁体   English   中英

Angular指令控制器作用域可见性

[英]Angular directive controller scope visibility

为什么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

正如您在指令注释中指出的那样,它具有隔离的作用域,因此, monkey键附加的值可用于指令作用域,而不是控制器一。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM