1

我正在尝试从组件调用控制器的功能。这是我的文件:

控制器.js:

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

视图.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>
4

2 回答 2

2

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

如果您想调用父范围/控制器范围内的函数,请执行以下操作

在您的控制器中考虑以下方法:

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. 使用 $scope 注入创建一个名为“NotesController”的控制器,因为组件是控制器的子级,控制器“scope”可以作为组件中的 $parent 访问。

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

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

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

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

    <notes note="obj.notes"/>
    

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

希望这可以帮助!干杯...

于 2017-03-26T23:15:25.920 回答
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 组件文档

很好地解释了组件和指令之间的差异

于 2017-04-26T17:49:09.753 回答