Nilai lingkup direktif (nilai awal dan judul) adalah undefined dalam fungsi pengontrol saya - counterController. Ini mencetak initialValue jika saya mendefinisikannya seperti {{ counterCtrl.initialValue }} di app_counter.directive.html, tetapi undefined di counterController fungsi.

app_counter.directive.js

'use strict';

module.exports = function (app) {
    app.directive('appCounter', appCounter)
};

function appCounter() {
    let directive = {
        restrict: 'EA',
        template: require('./app_counter.directive.html'),
        scope: {
            initialValue: '=',
            title: '@'
        },

        controller: counterController,
        controllerAs: 'counterCtrl',
        bindToController: true
    };

    return directive;
}

function counterController() {
    let vm = this;

    vm.counter = vm.initialValue;
    vm.increment = increment;
    vm.decrement = decrement;

    function increment() {
        vm.counter += 1;
    }

    function decrement() {
        vm.counter -= 1;
    }
}

app.js

'use strict';

const angular = require('angular');
const app = angular.module('app', []);

require('./app_counter/app_counter.directive')(app);

app_counter.directive.html

<div class="counter">
    <div>Current value {{counterCtrl.title}}: {{ counterCtrl.counter }}</div>
    <button type="button" ng-click="counterCtrl.decrement()">Decrement</button>
    <button type="button" ng-click="counterCtrl.increment()">Increment</button>
</div>

index.html

<div id="app" ng-app="app">
    <app-counter title="hello" initial-value="10"></app-counter> 
</div>
1
Yevhen Radionov 9 November 2017, 19:43

1 menjawab

Jawaban Terbaik

Anda perlu mengaksesnya dengan $scope (sebagaimana adanya) di dalam pengontrol Anda alih-alih menggunakan objek instance pengontrol Anda (this) secara langsung.

function counterController($scope) {
    let vm = this;

    vm.counter = $scope.initialValue;
    vm.increment = increment;
    vm.decrement = decrement;

    function increment() {
        vm.counter += 1;
    }

    function decrement() {
        vm.counter -= 1;
    }
}

>> Demo biola


Dengan menggunakan bindToController:

Anda dapat mencapai hal yang sama dengan menggunakan bindToController yang tersedia sejak AngularJS v1.3:

myApp.directive('myDirective', function () {
    return {
      restrict: 'A',
      scope: true,
      controllerAs: 'counterCtrl',
      bindToController: {
        initialValue: '='
      },
      controller: function () { 
        this.$onInit = function () {

            let vm = this;

            vm.counter = vm.initialValue;
            vm.increment = increment;
            vm.decrement = decrement;

            function increment() {
                vm.counter += 1;
            }

            function decrement() {
                vm.counter -= 1;
            }
        };
      }
    }
});

>> Demo biola

2
lin 9 November 2017, 17:20