2017-07-24 87 views
1

我遇到問題。我在AngularJs中創建了一個組件,我想將數據從控制器傳遞給組件。從控制器獲取數據到組件AngularJs

數據來自模板組件,但組件中的控制器未定義!

這是我的代碼。

控制器

angular.module('testModule') 
.controller('testController', ['$scope', 
    function($scope){ 
     var vm = this; 
     vm.name = "John"; 
    } 
]); 

的組件。這裏在console.log(vm.name)其未定義!這是我的問題。

angular.module('testModule') 
    .component('testComponent', { 
     bindings: { 
      "name": '=' 
     }, 
     controllerAs: 'ctrl', 
     controller: ['$scope', function ($scope) { 

      var vm = this; 
      console.log(vm);    
      console.log(vm.name); 
     }], 
     template: "<h2>Hi {{ctrl.name}}</h2>", 
    }); 

HTML

<html ng-app="testModule"> 
<head> 
    <title>Test</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script> 
    <script src="app.module.js"></script> 
    <script src="testController.js"></script> 
    <script src="testComponent.js"></script> 
</head> 
<body> 
<div ng-controller="testController as ctrl"> 
    <test-component name="ctrl.name"></test-component> 
</div> 
</body> 
</html> 

這裏是Plunker

任何想法?謝謝!

回答

0

您應該連接$onInit方法以查看bindings有哪些組件。

vm.$onInit = function(){ 
    console.log(vm.name); 
} 

你試圖做的事情是完全可行的,直到角1.5.X,但由於AngularJS 1.6+版本它們禁用預填充控制器超過$compileProvider引入preAssignBindingsEnabled上下文。默認情況下它被設置爲false。如果你真的想看到這個工作,你可以嘗試通過下面的代碼設置標誌(但我不建議使用這個)。引入這一變化的主要原因是讓Angular和AngularJS API的設計看起來類似於&體系結構,最終它將向Angular遷移更近一步。

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

Plunker

+0

它的獨特的形式來做到這一點? – ZizouJd

+0

@JhonnyAfonso檢查更新的說明 –

+0

感謝您的解釋!問候 – ZizouJd

相關問題