Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple directive to show name of user not working

I have made a simple example of custom directive to show name of a person. It still is not showing it. Can someone help?

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl"> 
    <person></person> 
<script>
    //module declaration
    var app = angular.module('myApp',[]);
    //controller declaration
    app.controller('myCtrl',function(){
        $scope.name = "Peter";
    });
    //directive declaration
    app.directive('person',function(){
      return {
        restrict: 'E',
        template: '<div>' {{ name }} '</div>' 
       };
    });
</script>
</body> 
</html>
like image 871
Deadpool Avatar asked Mar 13 '23 13:03

Deadpool


1 Answers

You just need to use proper Javascript syntax. I'm talking about string concatenation (which you don't need). You also forgot to inject $scope into controller. Correct syntax:

// module declaration
var app = angular.module('myApp', []);

// controller declaration
app.controller('myCtrl', function($scope) {
  $scope.name = "Peter";
});

// directive declaration
app.directive('person', function() {
  return {
    restrict: 'E',
    template: '<div>{{name}}</div>'
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <person></person>
</div>

Above will work for you, but this is just simple syntax stuff. More importantly is that you should not write such kind of directives, simply because they don't add real value. You could have just written {{name}} in template without directive at all.

Now useful directive would look something like this:

// module declaration
var app = angular.module('myApp', []);

// controller declaration
app.controller('myCtrl', function($scope) {
  $scope.user = {
    name: "Peter",
    age: 12,
    hobby: "Coding, reading"
  };
});

// directive declaration
app.directive('person', function() {
  return {
    scope: {
      data: '='
    },
    template: 
      '<div>{{data.name}}, {{data.age}}</div>' +
      '<small>{{data.hobby}}</small>'
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <person data="user"></person>
</div>

In the above example, you isolate scope of the directive (so it becomes an UI component), making it truly reusable and flexible. Prefer this approach.

like image 198
dfsq Avatar answered Mar 23 '23 06:03

dfsq