简体   繁体   中英

Load angularjs controller dynamically from html

I have 2 controllers. I get a composite JS object which has some elements+JS objects+numerous arrays from the first controller

I want to initialize the 2nd controller multiple times with various array objects respectively.

I am using this code to iniatialize the 2nd controller.

app.controller('SSController', function($scope) {
$scope.init = function(initData)
{
    $scope.initData = initData;     
};

<div ng-controller="TTController">
    <div ng-controller="SSController" ng-init='init({currData})'>
    </div>
</div>

where currData is a property of the scope object of TTController.

If I pass a hardcoded number in the init, it gets passed, but not the currData object. Even an integer value which comes from currData, such as currData.id is not getting passed.

Any ideas how this is done ?

I think you should be writing a directive and not a controller. Please consider the following pattern.

<div ng-controller="TTController">
    <div my-process-array="dataToWatch">
    </div>
</div>

then

app.directive('myProcessArray', function(){
    return function(scope, elem, attrs){
         elem.bind('click', function(){
             // do click stuff 
         });

         scope.$watch(attrs.myProcessArray, function(newdata, olddata){
               // do stuff with data from the parent controller.
          });
    };       
});

Instead, define some service which holds the data; Initially,inject the service in to the TTController and then modify/fill in the data and then inject the same service into the SSController.. :) Use of Services is better compared to directives and controllers.. And by the way services are the better means to serve the data.. :)

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