2017-07-20 46 views
0

我想在角度Js的控制器內創建控制器。但我的代碼不起作用。請幫助我。如何以角度js在控制器內創建控制器

控制器:下面

app.controller('MainController',function($rootScope,$scope){ 
    console.log('MainController Created'); 
    $scope.test = "Success"; 

    app.controller('InnerController',function($scope){ 
     console.log('Inside the InnerController'); 
     console.log($scope.test); 
    }) 
}); 

是我的html正文:

<body> 
    <div ng-app="myApp" ng-controller="MainController"> 
     Enter your Name : 
     <input type="text" ng-model="name" placeholder="your name"> 
     <div ng-show="name"> 
      <h2>This is called Two way binding :: {{name}}</h2> 
     </div> 
     <div ng-controller="InnerController"> 
      <h2>{{name}}</h2> 
     </div> 
    </div> 
</body> 
+0

你不能像這樣創建嵌套控制器......但是你可以注入一個到另一個。 – Sankar

+0

您能否請幫我用一段代碼在另一個控制器中注入一個控制器@SankarRaj –

回答

0

您不能創建另一個控制器內部的控制器。但是你可以將DOM元素與不同的控制器嵌套在一起。所以,你應該你的控制器的聲明改成這樣:

app.controller('MainController',function($rootScope,$scope){ 
    console.log('MainController Created'); 
    $scope.test = "Success"; 
}); 

app.controller('InnerController',function($scope){ 
    console.log('Inside the InnerController'); 
    console.log($scope.test); 
}); 

注重的是test仍處於InnerController可用。

1

你應該把你的內心控制器聲明MainController之外,因爲他們都需要被初始化HTML解析

app.controller('MainController',function($rootScope,$scope){ 
    console.log('MainController Created'); 
    $scope.test = "Success"; 
}); 

app.controller('InnerController',function($scope){ 
    console.log('Inside the InnerController'); 
    console.log($scope.test); 
}); 
1

之前在HTML像你這樣主要是innercontroller 的父親控制器,但在角度它是這樣的控制器:

app.controller('MainController',function($rootScope,$scope){ 
    console.log('MainController Created'); 
    $scope.test = "Success"; 
}); 


app.controller('InnerController',function($scope){ 
     console.log('Inside the InnerController'); 
     console.laog($scope.test); 
    })