ng-model外部控制器

时间:2014-12-15 14:41:44

标签: javascript angularjs angularjs-ng-model

我正在尝试编辑ng-controller元素之外的视图。我能够通过使用$rootScope和dom操作来解决它,但我想知道如何通过原生angularjs解决它?

HTML:

  <body>
    <div class="container">
      <div class="block" ng-controller="BlockController as block">
          <div><strong>Name:</strong> {{ block.name }}</div>
          <a href ng-click="block.edit()">Edit</a>
      </div>
    </div>


    <div class="container-editor">
      <div id="block-editor"></div>
    </div>
  </body>

JS:

  angular.module('app', [])

  .controller('BlockController', BlockController);

  function BlockController($compile, $scope)
  {
      this.name = 'default name';

      this.edit = function() {
          var $editor_html = ' <input type="text" ng-model="block.name" name="name" /> <a href ng-click="block.save()">Save</a>';

          $editor_html = $compile($editor_html)($scope);
          angular.element(document.querySelector("#block-editor")).html('').append($editor_html);
      };

      this.save = function() {
          // save block
          angular.element(document.querySelector("#block-editor")).html('');
      };

  }

plnkr

这是示例

1 个答案:

答案 0 :(得分:0)

更有棱角的方式? 只需使用指令。 基本上,您可以在子指令中获取父指令的控制器*。 将父控制器视为其子/子的API。

.directive('parent', function() {
  return {
    controller: function() {
      this.catchChild = function(child) {
          // code...
      };
    }
  };
})
.directive('child', function() {
  return {
    require: '^parent',
    link: function($scope, $element, $attrs, parentController) {
      $scope.jump = function() {
        // I'm jumping...
        parentController.catch($scope);
      };
    }
  };
})

我为您更新了您的plnkr: http://plnkr.co/edit/qRURHRMWt9K5acLWmCHv?p=preview

(*)您可以将多个指令作为数组传递

angular.module('app', [])
.directive('parent1', function() {
    return {
        controller: function() {
            this.fn1 = function(child) {
                // code...
            };
        }
    };
})
.directive('parent2', function() {
    return {
        controller: function() {
            this.fn2 = function(child) {
                // code...
            };
        }
    };
})
.directive('child', function() {
    return {
        require: ['^parent1', '^parent2'],
        link: function($scope, $element, $attrs, controllers) {
            var parent1Controller = controllers[0];
            var parent2Controller = controllers[1];
            parent1Controller.fn1();
            parent2Controller.fn2();
        }
    };
})