2016-09-23 57 views
1

我试图从组件调用控制器的功能。下面是我的文件:从组件调用控制器的功能

controller.js:

$scope.dataTableDevices = { 
    title: 'title', 
    color: {'background' : 'rgb(31, 119, 180)'}, 
    items: [0, 1, 2] 
}; 
$scope.hacerClick = function(){ 
    alert("it works"); 
} 

view.html:

<device-categories data="dataTableDevices"></device-categories> 

deviceCategories.js:

function deviceCategoriesController() { 
} 

widgetsFactory.component('deviceCategories', { 
    templateUrl: 'app/common/js/components/deviceCategories/deviceCategories.html', 
    controller: deviceCategoriesController, 
    bindings: { 
     data: '=' 
    } 
}); 

deviceCategories.html:

<md-button ng-click="howToCallhacerClick()"> 
    Click 
</md-button> 
+0

检查http://stackoverflow.com/questions/18378520/angularjs-pass-function-to-directive – Shreyas

+0

我一直无法解决这个问题。组件的行为与指令有点不同,对吧? –

回答

0

组件就像具有隔离范围的指令。

如果你想调用的函数,而在父范围/控制器的范围,然后执行以下操作

考虑您的控制器下面的方法:

angular.module('MyApp').controller('AppController', function ($scope) { 
    $scope.validateInputByUser = function (obj) { 
     if (obj['note'].length > 255) { 
      return false; 
      } 
      return true; 
     }; 
}); 
  1. 创建一个组件

    angular.module('MyApp') 
    .component('notes', { 
             templateUrl: "/Templates/Notes.html", 
             controllerAs: 'model', 
             controller: NotesController, 
             bindings: { 
              note: '=' 
    }}); 
    
  2. 用名称'NotesController'创建一个名为'NotesController'的控制器$ scope注入,作为组件是控制器的子组件,控制器的作用域可以在组件中作为$ parent访问。

    function NotesController ($scope) { 
        // binding parent method to scope of current component 
        $scope.validateInputByUser = $scope.$parent.validateInputByUser; 
    }; 
    
  3. 现在,你可以实现并通过以下访问控制器方法:

    的Html上的音符模板(/Templates/Notes.html)看起来像

    <textarea type="text" ng-model="model.note" ng-blur="validateInputByUser(model)"/> 
    

    的Html上组件实施页面看起来像

    <notes note="obj.notes"/> 
    

现在,每次用户输入文本并离开文本区时,控制器的函数“validateInputByUser”将被调用。

希望这会有所帮助!干杯...

0

您需要使用'&'绑定将控制功能传递给您的组件,该组件用于回调组件事件。所以,你需要做这样的事情:

组件

.component('deviceCategories',{ 
    template: `<div> 
        <md-button ng-click="$ctrl.hacerClickFn()">Click Me! 
        </md-button> 
       </div>, 
    bindings: { 
     data:'=', //assuming you need two way binding 
     hacerFunc:'&' 
    }, 
    controller: [function(){ 
     var ctrl = this; 

      ctrl.hacerClickFn = function() { 
       ctrl.hacerFunc(); 
      } 
    }] 
}); 

查看

<device-categories data="data" hacer-func="hacerClick()"</device-categories> 

AngularJS Component Documentation

Great explanation of differences between components and directives

相关问题