【问题标题】:AngularJS Custom directives - Issue accessing controllerAs variables/objects in directive linkAngularJS自定义指令-在指令链接中访问controllerAs变量/对象的问题
【发布时间】:2018-05-27 06:26:54
【问题描述】:

我刚刚开始重构我的代码以在指令中执行 DOM 操作和函数,而不是像以前那样在控制器内部执行,但是我在访问使用控制器定义的变量/对象时遇到了问题控制器内的“this”语法我需要从那里继承它们。

我尝试使用如下的 bindToController,在其中添加了指令函数中使用的不同对象,但是当我尝试在“链接”中访问这些对象时,它们都以未定义的形式返回控制台。

这里的例子。在控制器中定义的“this.test”,尝试在控制台日志消息中的指令中访问它。

控制器:

app.controller('notificationsController', function($scope, $state, $http, $document, $mdDialog, $filter, $timeout, $mdToast) {

  this.test = 'TEST';

指令:

app.directive('clearNotifications', function($mdDialog, $mdToast, $timeout) {
return {
    controller: 'notificationsController', 
    controllerAs: 'notifications',
    scope: {},
    bindToController: {
        notifications: '=',
        filters: '=',
        test: '@'
    },
    restrict: 'A',
    link: function(scope, element, attrs) {
        element.bind('click', function() {

            console.log('notifications.test string test: ' + notifications.test);

【问题讨论】:

    标签: javascript angularjs model-view-controller angularjs-directive


    【解决方案1】:

    控制器中的this与指令中的controllerAs不同,指令中应使用ctrlmodel进行绑定。

    var app = angular.module("app", []);
    
    app.controller("notificationsController", function($scope) {
      this.test = "foo!";
    })
    
    app.directive("clearNotifications", function() {
      return {
        controller: 'notificationsController',
        controllerAs: 'notifications',
        scope: {},
        bindToController: {
          notifications: '=',
          filters: '=',
          test: '@'
        },
        restrict: 'A',
        link: function(scope, element, attrs, ctrl) {
          element.bind('click', function() {
            console.log('notifications.test string test: ' + ctrl.test);
          })
        }
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app">
      <button clear-notifications>clearNotifications</button>
    </div>

    【讨论】:

    • 我尝试在控制器中添加 self = this, self.test = 'TEST' 并在指令中使用 ctrl.test,但它仍然返回 undefined
    • 请用这个示例编译你的代码,看看它们之间有什么不同
    • 唯一的区别是控制器名和指令名
    • link 函数的最后添加 ctrl 作为指令中的参数
    • 我把它改成你的样本!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多