Angular JS访问相关控制器来自指令内



与这样的html ...

<div ng-app="myApp">
    <div ng-controller="inControl">
        I like to drink {{drink}}<br>
        <input my-dir ng-model="drink"></input>
    </div>
</div>

和这样的javascript ...

var app = angular.module('myApp', []);
app.controller('inControl', function($scope) {
    $scope.drink = 'water';
});
app.directive('myDir', function(){
    return {
        restrict: 'A',
        link: function($scope, element, attrs, ctrl) {
            // why is this logging undefined?
            console.log(ctrl);
        }
    };
});

为什么我在指令中不访问控制器?为什么我打电话给ctrl给我不确定?


编辑:添加演示...

小提琴可用:http://jsfiddle.net/billymoon/ve9dx/

请参阅一个应用程序可以连接多个控制器,并且可以与一个应用程序一起附上类似的多个指令,因此,如果您想在一个指令中使用一个控制器,则可以设置一个控制器您想要在您的案例中使用的控制器名称的指令

app.directive('myDir', function(){
    return {
        restrict: 'A',
        controller: 'inControl'
        link: function($scope, element, attrs, ctrl) {
            // why is this logging undefined?
            console.log(ctrl);
        }
    };
});

尽管使用了require:ngModel,但这仍然不是最佳方法,因为它直接将指令与控制器联系起来。如果您希望您的指示与控制器通信,则可以设置并阅读范围。

html:

<div ng-app="myApp">
  <div ng-controller="inControl">
    I like to drink {{drink}}<br />
    <input my-dir="drink"></input>
  </div>
</div>

JS:

var app = angular.module('myApp', []);
app.controller('inControl', function($scope) {
    $scope.drink = 'asdfasdf';
});
app.directive('myDir', function(){
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            console.log(scope[attrs.myDir]);
        }
    };
});

另外,您可以使用my-dir="{{drink}}"并将其读为attrs.myDir

http://jsfiddle.net/8ul6n/1/

添加require: 'ngModel',为我修复了它 - 不确定是否有另一种指定的方法...

app.directive('myDir', function(){
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function($scope, element, attrs, ctrl) {
            // why is this logging undefined?
            console.log(ctrl);
        }
    };
});

最新更新