简体   繁体   中英

How to access scope from controller to custom directive in Angular?

I am studying Angular now and I am in the directive lesson. And I am doing some exercise for myself but I have a problem.

I created a customer directive and what I want is the user will input any text in the textbox then the text from the input will be displayed in my custom directive.

Right bow I still don't get it.

Here's some of my code:

 <body ng-app="myApp">
    <div class="container" ng-controller="MainCtrl">
      <h3>Directive</h3>
      <div class="form-group">
        <label>Type text: </label>
        <input type="text" class="form-control" ng-model="greet_value" />
        <p>Value <div flx-greet-me></div></p>
      </div>
    </div>
  </body>

my directive:

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

myApp.controller('MainCtrl', function(){
  //some codes here
})
.directive('flxGreetMe', function() {

  var html_template = '<h1>' + $scope.greet_value + '</h1>';

  return {
    replace: true,
    restrict: 'AE',
    scope: true,
    template: html_template
  }

});

Can you help me with this? I am still new in Angular.

Here's the plnkr:

http://plnkr.co/edit/AugJkl?p=preview

Your problem is, obscurely, here:

scope: true,

What that does is isolate this directives scope from everything else. You could remove it and then do this:

 return {
    replace: true,
    restrict: 'AE',
    template: html_template,
    controller : function($scope) {
       $scope.$watch("greet_value", function(greet_value) {
         // whatever you like
       });
    }
  }

Or you could leave it and access the parent scope manually, like this:

 return {
    replace: true,
    restrict: 'AE',
    template: html_template,
    scope: true,
    controller : function($scope) {
       $scope.$parent.$watch("greet_value", function(greet_value) {
         // whatever you like
       });
    }
  }

Or you could make it more flexible by writing the view like this:

    <p>Value <div flx-greet-me="greet_value"></div></p>

And then

 return {
    replace: true,
    restrict: 'AE',
    template: html_template,
    scope: true,
    controller : function($attrs) {
       $attrs.flxGreetMe.$observe(function(arg_value) {
         // whatever you like
       });
    }
  }

(None of this code is tested.)

you can also use isolate scope and use '=' in the scope which provides you two way binding in your directive like as shown below

  <input type="text" ng-model="val"/>
  <p  value="val"></p>  

    return {
    replace: true,
    transclue: true,
    scope:{

     value = "="

     },
     template : "<div>value</div>"

refer : https://docs.angularjs.org/guide/directive

The simplest way to achieve you task is

HTML

    <p><input type="text" ng-model="inputValue" ng-keyup="setDirectiveValue(inputValue)"></p>
    <p><div my-directive></div></p>

    <script src="libs/angular-1.3.15/angular.min.js"></script>
    <script src="scripts/ctrlToDirectiveApp.js"></script>

ctrlToDirectiveApp

var myApp = angular.module("ctrlToDirective",[]);

myApp.controller("myCtrl", function($sce, $window, $scope){

    $scope.myDirectiveValue = "";

    $scope.setDirectiveValue = function(directiveValue){
        console.log(directiveValue);
        $scope.$watch(function(){
            $scope.myDirectiveValue = directiveValue;

        })
        console.log($scope.myDirectiveValue);
    };

})

myApp.directive("myDirective",function(){

    return {
        restrict: 'AE',
        template : "Hello {{myDirectiveValue}}"
    };

Well you can achieve the same things using isolated scope's two way data binding.

JS :

myApp.controller('MainCtrl', function($scope){
  //some codes here
  $scope.greet_value = "Please change text"
})
.directive("flxGreetMe", function() {

  return {
    replace: true,
    restrict: 'AE',
    scope : {test : "="},
    template: '<h1>{{test}}</h1>' 
  }  

});

HTML :

<div flx-greet-me  test="greet_value" >
           </div>

Here is the plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM