简体   繁体   中英

Assigning a controller from a directive angularjs 1.2

I'm switching from angularJS 1.0 to 1.2 and I'm having some trouble assigning a controller to a directive with a clean scope, without defining a controller in my html with ng-controller.

consider the following scenario:

var myApp=angular.module('myApp',[])
.controller('parentCtrl',function($scope,$element,$attrs) {
  $scope.helloworld = function(){                                                   
    console.log('hello world from ParentCtrl controller')
  }
})

.controller('childCtrl',function($scope,$element,$attrs) {
    $scope.helloworld = function(){ 

       console.log('hello world from ChildCtrl controller')

    }
})
.directive('ngParent', function() {
  return {
    controller:'ParentCtrl'
  }
})
.directive('ngChild', function() {
  return {
      controller:'ChildCtrl',
      scope:{},
      link:function(scope,element,attrs){

      }
   }
})

And HTML:

  <body ng-app="myApp" ng-parent>
      <button ng-click="helloworld()">Parent Scope click </button>
      <div ng-child>
         <button ng-click="helloworld()">Child Scope click </button>
      </div>  
  </body>

Right now, both buttons will log "hello world from ParentCtrl controller". However, if I change the parameter scope:{} to scope:true in the ngChild directive, it works and the buttons are calling their respective scopes' helloworld function. But that doesn't make a clean scope like I want it to.

How do I make a clean scope in a directive with angular 1.2, without assigning the controller in my view?

Thanks, Andreas

because you're not creating a new scope both directives are using the same scope and the definition of "helloworld" function gets overwritten. so either you need to change the name of the function or create a new scope,

and by the way i think you're using directives wrong. instead of defining directives and assign controllers to them you should use ng-controller and for each of controllers set the helloworld function in their own scopes. and write a directive (if it's really needed) to get that function and call it when you need to.

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