指令绑定未定义

时间:2016-07-05 12:23:25

标签: javascript angularjs

我对angularjs有点新鲜。我正在写一个指令,但我无法理解bindToController是如何运行的。我阅读了这篇有用的文章http://blog.thoughtram.io/angularjs/2015/01/02/exploring-angular-1.3-bindToController.html,但我无法理解为什么在以下示例中我未定义。

.directive('firstDirective', function(){
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        bindToController: {
            directiveInput:'='
        },
        templateUrl: 'components/directive-tree/directive-tree.html',
        controllerAs: 'directiveTreeCtrl',
        controller: function($scope, $uibModal){
            var self = this;
            self.selected = null;
            console.log(self.directiveInput); //HERE IS THE UNDEFINED
            $scope.modalOptions = {
                windowClass: 'semi-modal',
            }

            this.openDirectiveModal = function(object, index) {
                //Other irrelevant code
            }
        }
    } 
 });

之后,我可以毫无问题地使用HTML模板的输入。

<ul>
    <li ng-repeat="object in directiveTreeCtrl.directiveInput">
        {{object.Id}}&emsp;{{object.Name}}
    </li>
</ul>

为什么在HTML模板中我可以使用directiveInput并使用正确的值进行实例化,我的console.log显示我&#34; undefined&#34;?

也许这是一个愚蠢的问题。谢谢

1 个答案:

答案 0 :(得分:1)

通常,为实现此目的而编写的代码如下:

.directive('firstDirective', function(){
    return {
        restrict: 'E',
        replace: true,
        scope: {
            directiveInput:'='
        },
        bindToController: true,
        templateUrl: 'components/directive-tree/directive-tree.html',
        controllerAs: 'directiveTreeCtrl',
        controller: function($scope, $uibModal){
            var self = this;
            self.selected = null;
            console.log(self.directiveInput); //HERE IS THE UNDEFINED
            $scope.modalOptions = {
                windowClass: 'semi-modal',
            }

            this.openDirectiveModal = function(object, index) {
                //Other irrelevant code
            }
        }
    } 
 });

现在是HTML

<first-directive directive-input="inputObject"></first-directive>