Get value from ng-model from custom directive

0

Help to get the value from a custom-directive

I have the following code, all I need is to be able to get the value that the text field gets when it is type.

The getName function should change the displayed name.

I add the code:

'use strict';

angular
 .module('app', [])
 .controller("Controller", function ($scope) {
  $scope.getName = function() {
   return $scope.name;
  };
 })
 .controller("EditController", function($scope) {
  $scope.editingMode = true;
 })
 .directive("newName", function ($parse) {
  return {
  template: 'Write name: <input type="text" ng-model="name">'
 };
});

            Angular                

<div ng-controller="Controller">
  <h1>Hello, {{ getName() }}</h1>

  <div ng-controller="EditController">
    <new-name ng-show="editingMode"></new-name>
  </div>
</div>

    
asked by Hector Manuel Cabrera Villa 26.09.2017 в 01:58
source

1 answer

0

You have to specify that the policy is an element using restrict: 'E' :

'use strict';

angular
    .module('app', [])
    .controller("Controller", function($scope) {
        
        $scope.getName = function() {
            return $scope.name;
        };
    })
    .controller("EditController", function($scope) {
        $scope.editingMode = true;
        
    })
    .directive("newName", function($parse) {
        return {
            restrict:"E",
            template: 'Write name: <input type="text" ng-model="name">'
        };
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="Controller" ng-app="app">
  <h1>Hello, {{ getName() }}</h1>

  <div ng-controller="EditController">
    <new-name></new-name>
    {{name}}
  </div>
</div>

And as you may have noticed, it does not update the titul where you have {{ getName() }} , this because the methods do not respond to the update of the model. You have to specify the model to update the title. In other words, replace {{ getName() }} with {{ name }} :

'use strict';

angular
    .module('app', [])
    .controller("Controller", function($scope) {
        
        $scope.getName = function() {
            return $scope.name;
        };
    })
    .controller("EditController", function($scope) {
        $scope.editingMode = true;
        
    })
    .directive("newName", function($parse) {
        return {
            restrict:"E",
            template: 'Write name: <input type="text" ng-model="name">'
        };
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="Controller" ng-app="app">
  <h1>Hello, {{ name }}</h1>

  <div ng-controller="EditController">
    <new-name></new-name>
    {{name}}
  </div>
</div>
    
answered by 26.09.2017 в 15:04