2016-12-21 9 views
3

変数がディレクティブコントローラに定義されていない理由を私は理解できません。変数がディレクティブコントローラで定義されていないのはなぜですか?

'use strict'; 
 

 
angular 
 
    .module('app', []) 
 
    .directive('myExample', myExample, ['$scope']); 
 

 
function myExample() { 
 
    var directive = { 
 
     restrict: 'E', 
 
     template: '<span>{{vm.date}}</span>', 
 
     scope: {}, 
 
     controller: ExampleController, 
 
     controllerAs: 'vm', 
 
     bindToController: { 
 
      date: '@' 
 
     } 
 
    }; 
 

 
    return directive; 
 
} 
 

 
function ExampleController($scope) { 
 
    var vm = this; 
 

 
    // I need here some code with vm.date 
 
    // BUT vm.date is undefined 
 
    // Why? 
 
    console.log('Ctrl: %s', vm.date); 
 

 
    $scope.$watch('vm.date', function (newValue, oldValue) { 
 
     // vm.date is 777 
 
     console.log('Ctrl: %s | %s', oldValue, newValue); 
 
    }); 
 
}
<body ng-app="app"> 
 
    <my-example date="777"></my-example> 
 

 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script> 
 
</body>

vm.dateが定義されていないのはなぜ?どのようにそれが定義されたことを行うには?

linkと同じ方法を使用しようとしました。問題ない。

答えて

5

ExampleControllerが構築された時点でバインディングが存在しないためです。あなたが$onInitを使用する必要があるバージョン1.6以来:

function ExampleController($scope) { 
    var vm = this; 

    this.$onInit = function() { 
    console.log('Ctrl: %s', vm.date); 
    } 
} 

そして$scopeを削除するには、(それを避けるため)全くそれを必要としません。これは、それが今からになります方法です(そしてそれがどのように角度2である)として

.config(function($compileProvider) { 
    $compileProvider.preAssignBindingsEnabled(true); 
}); 

が、より良いスイッチ$onInitオプションへ:

また、あなたは$compileProviderpreAssignBindingsEnabled設定で古い結合挙動を再度有効にすることができます。

+0

私はテストに '$ scope'を使います。お手伝いありがとう!これは '$ onInit'で動作します。私は 'vm。$ onInit'がより良いと思います。 – raciasolvo

関連する問題