Angular ngController vs Controller constructed within Directive

前端 未结 4 1294
被撕碎了的回忆
被撕碎了的回忆 2021-01-04 19:06

I\'m wondering what the use cases are for these two methods of creating a controller:

Using ngController:

myApp.controller(\'myContr         


        
4条回答
  •  攒了一身酷
    2021-01-04 19:52

    Adding some detail regarding accessing methods and values within the directive controller:

    Parent directive

    myApp.directive ( 'parent', [ function() {
        return {
            restrict: 'A',
            scope: {},
            controller: [ '$scope', function( $scope ) {
                //this.myVar = ''; //accessible in child directives
                //$scope.myVar = ''; //accessible in template
                $scope.myVar = this.myVar = '';
            }],
            template: '
    {{myVar}}
    ', link: function( scope, element, attrs ) { console.log( scope.myVar ); } }; }]);

    Child directive

    myApp.directive ( 'child', [ function() {
        return {
            restrict: 'A',
            require: '^parent',
            link: function( scope, element, attrs, ctrl ) {
    
                console.log( ctrl.myVar );
    
            }
        };
    }]);
    

提交回复
热议问题