1

不使用孤立范围时如何访问This指令及其模板内的控制器?

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

1 回答 1

1

简单地将其解析为controller as instance value您的指令范围,就像在这个简单的小提琴演示中一样:

看法

<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);
    }
  }
});

另一种方法是通过使用controller:'MyCtrl as ctrl'like in this demo fiddle将您的控制器解析为指令。

看法

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 }}'
  }
});

您还可以将洞控制器实例解析到范围内并像在这个演示小提琴中一样访问它。

看法

<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) {
    }
  }
});
于 2017-04-12T10:01:12.240 回答