简体   繁体   English

从HTML动态加载angularjs控制器

[英]Load angularjs controller dynamically from html

I have 2 controllers. 我有2个控制器。 I get a composite JS object which has some elements+JS objects+numerous arrays from the first controller 我从第一个控制器中获得了一个复合JS对象,其中包含一些元素+ JS对象+许多数组

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. 其中,currData是TTController范围对象的属性。

If I pass a hardcoded number in the init, it gets passed, but not the currData object. 如果我在init中传递了一个硬编码的数字,它将被传递,而不是currData对象。 Even an integer value which comes from currData, such as currData.id is not getting passed. 即使是来自currData的整数值(例如currData.id)也不会传递。

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.. :) 首先,将服务注入TTController,然后修改/填充数据,然后将相同服务注入SSController。.:)与指令和控制器相比,使用Services更好。表示服务数据.. :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM