簡體   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