在指令上定义我自己的“要求”,但抛出错误 - AngularJs

Defining my own 'require' on a directive, but throw error - AngularJs

本文关键字:出错 错误 AngularJs 要求 指令 定义 我自己 自己的      更新时间:2023-09-26

假设我有这个html

<div ng-controller="MyCtrl">    
    <br>
    <my-directive my-name="name">Hello, {{name}}!</my-directive>
</div>

使用这个简单的控制器

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

我有一个指令,我想使用这样的require来更改'name'

myApp.directive('myDirective', function($timeout) {
var controller = ['$scope', function ($scope) {
    $scope.name = "Steve";
}];
    return {
        restrict: 'EA',
        require: 'myName',
        controller: controller,
        link: function(scope, element, attrs, TheCtrl) {
            TheCtrl.$render = function() {
                $timeout(function() {
                    TheCtrl.$setViewValue('StackOverflow');  
                }, 2000);                
            };
        }
    };
});

但是抛出:

Error: No controller: myName

这是小提琴


但是如果我使用 ng 模型实现它,则可以工作。看看这里的另一个小提琴

我读过,如果您在指令中使用'require',则需要为其配备控制器。

所以:

我做的错了?不是这样吗?我需要做任何其他事情吗?

好吧,

我终于明白了。

从本质上讲,我正在尝试做的是所谓的:"使用控制器的指令之间的通信"。我找到了一篇解释这一点的文章,对我帮助很大:

观点:

<div ng-controller="MyCtrl">
 <br>
 <my-directive my-name>Hello, {{name}}!</my-directive>
</div>

正如您在上面看到的,有两个指令: my-directivemy-name .我将使用 requiremy-name指令的控制器调用my-directive函数。

我的指令:

myApp.directive('myDirective', function($timeout) {
 return {
  require: 'myName',
  link: function(scope, element, attrs, myNameCtrl) {
   $timeout(function() {
    myNameCtrl.setName("Steve");
   }, 9000);
  } // End of link
 }; // return
});

我的名字:

myApp.directive('myName', function($timeout) {
    var controller = ['$scope', function ($scope) {
        // As I tried, this function can be only accessed from 'link' inside this directive
        $scope.setName = function(name) {
            $scope.name = name;
            console.log("Inside $scope.setName defined in the directive myName");
        };
        // As I tried, this function can accessed from inside/outside of this directive
        this.setName = function(name) {
            $scope.name = name;
            console.log("Inside this.setName defined in the directive myName");
        };
    }];
    return {
        controller: controller,
        link: function(scope, element, attrs, localCtrl) {
            $timeout(function() {
                localCtrl.setName("Charles");
            }, 3000);
            $timeout(function() {
                scope.setName("David");
            }, 6000);
        } // End of link function
    };
});

有趣,就像一个魅力。如果您想尝试一下,这里是小提琴。

此外,您可以使用事件在指令之间获取通信。在SO上阅读此答案。

相关文章: