angularjs - A simple directive to show name of user not working -


i have made simple example of custom directive show name of person. still not showing it. can 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> 

you need use proper javascript syntax. i'm talking string concatenation (which don't need). forgot inject $scope 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 work you, simple syntax stuff. more importantly should not write such kind of directives, because don't add real value. have written {{name}} in template without directive @ all.

now useful directive 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 above example, isolate scope of directive (so becomes ui component), making reusable , flexible. prefer approach.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -