External ng model controller

I am trying to edit the look of ng-controller . I was able to solve this using the manipulations of $rootScope and dom, but I want to know how this can be solved using my own angles?

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

here is an example

+5
source share
1 answer

More angular way? Just use the directives . Basically, you can get the controller * of the parent directive inside the child directive. Treat the parent controller as an API for its children / children.

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

I updated your plnkr for you: http://plnkr.co/edit/qRURHRMWt9K5acLWmCHv?p=preview

(*) You can pass multiple directives as an array

 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(); } }; }) 
0
source

Source: https://habr.com/ru/post/1209112/


All Articles