想要将控制器与Angular中的主页相关联

时间:2015-05-20 19:14:17

标签: angularjs

我目前正在创建一个包含导航栏的应用。我想要在每次按下导航栏中的提交按钮时调用特定函数,而不管路径/视图如何。我遇到了麻烦,因为在我的路线文件中,我创建了基于路线改变的关联。该表单位于<form class="pure-form" ng-submit="somefunc()">

routes.js

angular.module('LiveAPP', ['ngRoute',
                          'LiveAPP.main',
                          'LiveAPP.signUp',
                          'LiveAPP.artist'])

.config(function($routeProvider, $httpProvider) {
$routeProvider
  .when('/', {
    templateUrl : '/home.html',
    controller  : 'mainCtrl'
  })
  .when('/signup',{
    templateUrl : '/signup.html',
    controller  : 'signUpCtrl'
  })
  .when('/artist',{
    templateUrl : '/artistpage.html',
    controller  : 'artistCtrl'
  })
})

的index.html

<body ng-app='LiveAPP'>
  <div class="header">

    <form class="pure-form" ng-submit="somefunc(field)">

      <input ng-model="field" type="text" placeholder="Artist" name="field">
      <button type="submit">Search</button>

    </form>

    <a href="/#/signup">Sign Up</a>
    <a href="/#/artist">artistPage</a>

  </div>

  <div ng-view></div>

</body>

mainCtrl

angular.module('LiveAPP.main',[])
.controller('mainCtrl', ['$scope','$http', '$location',mainCtrl]);

function mainCtrl($scope,$http,$location){
  $scope.somefunc = function(searchvalue){
    console.log(searchvalue)
  }

};

现在提交按钮与mainCtrl相关联,mainCtrl与home.html相关。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

一般来说,您有几种方法:

  1. 如果您需要在多个控制器中使用某些逻辑,则可以创建服务并将其注入控制器。
  2. 您可以实现控制器继承。
  3. 有几种方法可以实现控制器继承。 这是如何做到这一点的一个例子:

    var app = angular.module('myApp', []);
        app.controller('MainCtrl', function() {
        this.methodclick=function(){
          alert('I am Parents')
        }
       });
       app.controller('ChildCtrl', function($controller) {
       var ChildCtrl=this;
       ChildCtrl.child = $controller('MainCtrl',{});
       });
    

    但在我看来,最好是实施一项服务。