cs.matyi
cs.matyi

Reputation: 1264

AngularJS ng-model in custom directives

I'm creating a directive with ng-model. So I can pass the model to these directives.

Here is what I think about it:

app.js

app.directive('testDir', function(){
    return {
        templateUrl: 'assets/views/dir.html',
        restrict: 'E',
        required: 'ngModel'

    };
});

dir.html

<div>
    <h1>Test directive</h1>
    <h3>{{name}}</h3>
</div>

index.html

<div class="container" ng-controller="testCtrl">
  <test-dir ng-model="user"></test-dir>
</div>

and the contoller

$scope.user = {
        name: 'John Doe'
    };

I can see the <h1> tag with Test directive text but nothing in the <h3> tag

I know it is a very beginner problem, but right know I can't find any solution.

Thank you!

Upvotes: 1

Views: 37

Answers (2)

Shashank Agrawal
Shashank Agrawal

Reputation: 25817

The syntax for scope was missing. Please see a working example below

var app = angular.module("sa", []);

app.controller("testCtrl", function($scope) {
  $scope.user = {
    name: 'John Doe'
  };
});

app.directive('testDir', function() {
  return {
    //templateUrl: 'assets/views/dir.html',
    template: '<div>' +
      '<h1>Test directive</h1>' +
      '<h3>{{fooModel.name}}</h3>' +
      '</div>',
    restrict: 'E',
    required: 'ngModel',
    scope: {
        fooModel: '=ngModel'
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" class="container" ng-controller="testCtrl">
  <test-dir ng-model="user"></test-dir>
</div>

Upvotes: 2

byteC0de
byteC0de

Reputation: 5273

Try This, you need to create a scope variable for ng-model

app.directive('testDir', function(){
        return {
            templateUrl: 'assets/views/dir.html',
            restrict: 'E',
            required: 'ngModel',
            scope: {
                ngModel:'='
            }

        };
    });

HTML

<div>
    <h1>Test directive</h1>
    <h3>{{ngModel}}</h3>
</div>

Upvotes: 2

Related Questions