0

I am following a course on Angular and as a complete newbie I have a newbie question to ask about custom directives. I wonder how can we set new variables in that custom directive and access them in our view, is that even possible, if somebody could explain that in a clear way?

For example:

myApp.controller('mainController', ['$scope', '$log', function($scope, $log) {

$scope.person = {
    name: 'John Doe',
    address: '555 Main St., New York, NY 11111'
}

}]);

myApp.directive("searchResult", function() {
return {
   restrict: 'AECM',
   templateUrl: 'directives/searchresult.html',
   replace: true,
   scope: {
       personName: "@",
       personAddress: "@",
       newVariable: "someValue"
   }
 }
});

searchresult.html

<a href="#" class="list-group-item">
<h4 class="list-group-item-heading">{{ personName }}</h4>
<p class="list-group-item-text">
    {{ personAddress }}
</p>
<p class="list-group-item-text">
    {{ newVariable }}
</p>

main.html

<label>Search</label>
<input type="text" value="Doe" />
 <h3>Search Results</h3>
<div class="list-group">
<search-result person-name="{{ person.name }}" person-address="{{ person.address }}" newVariable="{}"></search-result>

1
  • can you a bit explain what you expect? Commented Apr 8, 2016 at 9:06

2 Answers 2

1

use link function for local scope

myApp.directive("searchResult", function() {
return {
   restrict: 'AECM',
   templateUrl: 'directives/searchresult.html',
   replace: true,
   scope: {
       personName: "@",
       personAddress: "@"
   },
   link: function(scope, elem, attr) { scope.newVariable='something'; },
 };
});
Sign up to request clarification or add additional context in comments.

Comments

0

Use This.

       var app = angular.module("test",[]);
       app.controller("Ctrl1",function($scope){    $scope.name = "Abc";    $scope.reverseName = function(){
       $scope.name = $scope.name.split('').reverse().join('');    }; });

 app.directive("myDirective", function(){    return {
       restrict: "EA",
       scope: false,
       template: "<div>Your name is : {{name}}</div>"+
       "Change your name : <input type='`enter code here`text' ng-model='name' />"    }; });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.