Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angularjs - how to reuse a function in multiple controllers

I have multiple controllers for multiple routes:

app.controller('FirstController', function ($scope) {
  $scope.func = function () {
    console.log('route 1');
  }
}
app.controller('SecondController', function ($scope) {
  $scope.func = function () {
    console.log('route 2');
  }
}
...

and a directive that uses the $scope.func, this way:

app.directive('thedirective', function () {
  return {
    link: function (scope, $element, attrs) {
      $scope.func(attrs.thedirective);
    }
  }
});

$scope.func is different in each controller. I expect the $scope.func to log "route 1" when we are in route1 and FirstController is the current controller and to log "route 2" when in route 2, but only "rout 1" is what I get in console. may you please tell me why changing route doesn't change $scope of directive?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In AngularJS if function is being used common in controllers.

Best practises is use service or factory which will inject to controller.

app.factory('commonService', function ($scope) {
     var obj= {};
      obj.func = function () {
        console.log('route 1');
      }
     obj.func1 = function () {
        console.log('route 2');
      }
  return obj;
    }
    app.controller('FirstController', function ($scope,commonService) { 
        console.log('route 1' + commonService.func());  
    }
    app.controller('SecondController', function ($scope,commonService) { 
        console.log('route 2' + commonService.func1());  
    }

And when we talk about directive ,scope of the directive will be with one controller either directive controller or outside controller which we defined.

<div ng-controller="firstController">
<your-directive />
</div>

<div ng-controller="secondController">
<your-directive />
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...