使用controller作为内部指令模板时访问控制器

时间:2017-04-12 09:44:56

标签: angularjs controlleras

如果不使用isoloted范围,如何访问指令及其模板内的控制器This

app.controller('ChildCtrl', function() {
  this.name = "Name from children";
});

1 个答案:

答案 0 :(得分:1)

简单地将其解析为controller as instance value到您的指令范围内,例如 simple fiddle demo

视图

<div ng-controller="MyCtrl as ctrl">
  Hello, <span simple-directive data="ctrl.name"></span>!
</div>

AngularJS应用程序

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    this.name = 'Superhero';
});

myApp.directive('simpleDirective', function () {
  return {
    restrict: 'A',
    scope: {
      data: '='
    },
    template: '{{ data }}',
    link: function (scope, elem, attrs) {
        console.log(scope.data);
    }
  }
});

另一种方法是使用{strong> demo fiddle 中的controller:'MyCtrl as ctrl'将控制器解析为指令。

视图

Hello, <span simple-directive></span>!

AngularJS应用程序

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
  this.name = 'Superhero';
});

myApp.directive('simpleDirective', function () {
  return {
    restrict: 'A',
    controller:'MyCtrl as ctrl',
    template: '{{ ctrl.name }}'
  }
});

您也可以将孔控制器实例解析到范围内,并像在 demo fiddle 中一样访问它。

视图

<div ng-controller="MyCtrl as ctrl">
  Hello, <span simple-directive ctrl="ctrl"></span>!
  <br />
  <input type="text" ng-model="ctrl.name">
</div>

AngularJS应用程序

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($scope) {
    this.name = 'Superhero';
});

myApp.directive('simpleDirective', function () {
  return {
    restrict: 'A',
    scope: {
      ctrl: '='
    },
    template: '{{ ctrl.name }}',
    link: function (scope, elem, attrs) {
    }
  }
});