Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's actually pretty good logic but you can simplify things a bit.</p> <h3>Directive</h3> <pre><code>var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.model = { name: 'World' }; $scope.name = "Felipe"; }); app.directive('myDirective', function($compile) { return { restrict: 'AE', //attribute or element scope: { myDirectiveVar: '=', //bindAttr: '=' }, template: '&lt;div class="some"&gt;' + '&lt;input ng-model="myDirectiveVar"&gt;&lt;/div&gt;', replace: true, //require: 'ngModel', link: function($scope, elem, attr, ctrl) { console.debug($scope); //var textField = $('input', elem).attr('ng-model', 'myDirectiveVar'); // $compile(textField)($scope.$parent); } }; }); </code></pre> <h3>Html with directive</h3> <pre><code>&lt;body ng-controller="MainCtrl"&gt; This scope value &lt;input ng-model="name"&gt; &lt;my-directive my-directive-var="name"&gt;&lt;/my-directive&gt; &lt;/body&gt; </code></pre> <h3>CSS</h3> <pre><code>.some { border: 1px solid #cacaca; padding: 10px; } </code></pre> <p>You can see it in action with this <a href="http://plnkr.co/edit/A29hl6" rel="noreferrer">Plunker</a>.</p> <p>Here's what I see:</p> <ul> <li>I understand why you want to use 'ng-model' but in your case it's not necessary. ng-model is to link <em>existing</em> html elements with a value in the scope. Since you're creating a directive yourself you're creating a 'new' html element, so you don't need ng-model.</li> </ul> <p><strong>EDIT</strong> As mentioned by Mark in his comment, there's no reason that you <em>can't</em> use ng-model, just to keep with convention.</p> <ul> <li>By explicitly creating a scope in your directive (an 'isolated' scope), the directive's scope cannot access the 'name' variable on the parent scope (which is why, I think, you wanted to use ng-model).</li> <li>I removed ngModel from your directive and replaced it with a custom name that you can change to whatever.</li> <li>The thing that makes it all still work is that '=' sign in the scope. Checkout the docs <a href="http://docs.angularjs.org/guide/directive" rel="noreferrer">docs</a> under the 'scope' header.</li> </ul> <p>In general, your directives should use the isolated scope (which you did correctly) and use the '=' type scope if you want a value in your directive to always map to a value in the parent scope. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload