在bootstrap之后动态地将控制器分配给元素

时间:2015-08-19 18:26:52

标签: javascript angularjs ng-controller

我有一个AngularJS应用程序,我手动引导时间' t。在时间&#t; + 1',我想显示一个没有连接ng-controller的HTML元素。我想动态地将ng-controller添加到此元素中,以便它可以与我的javascript代码进行通信。

我该怎么做?

PS我尝试动态地将ng-controller属性添加到元素中,但它不起作用。

2 个答案:

答案 0 :(得分:3)

要做到这一点,你需要编译元素。

<强> HTML

<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.5/angular.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

    <link href="main.css" rel="stylesheet" type="text/css" />
    <script src="main.js"></script>
<meta charset=utf-8 />
<title>Angular JS</title>
</head>
<body ng-controller="parentCtrl">
    <button ng-click="setCtrl2()">Set Controller</button>
    <div id="placeholder">
        <span></span>
        <select>
            <option></option>
        </select>
        <span class="input-append">
            <input id="add" type="text" placeholder="Another one ?" ng-model="addName" />
            <input type="submit" class="btn btn-primary" ng-click="addRow()" value="+ add" />
        </span>
    </div>
</body>
</html>

<强>的Javascript

angular.module('app', []);

angular.module('app').controller('ctrl', function($scope) {
      $scope.rows = ['Paul','John','Lucie'];
        $scope.name = 'Jack';

      $scope.addRow = function(){
        $scope.rows.push($scope.addName);
        $scope.addName = "";
          console.log($scope.rows);
      };
})
.controller('parentCtrl', function($scope) {
    $scope.setCtrl2 = setCtrl;
});

function setCtrl() {
    var elem =  document.getElementById('placeholder');
    elem.setAttribute('ng-controller', 'ctrl');
    var eSpan = elem.children[0];
    var eSelect = elem.children[1].children[0];
    eSpan.setAttribute('ng-bind', 'name');
    eSelect.setAttribute('ng-repeat', 'row in rows');
    eSelect.setAttribute('value', '{{ row }}');
    eSelect.setAttribute('ng-bind', 'row');

    var injector = angular.element(elem).injector();
    var compile = injector.get('$compile');
    var rootScope = injector.get('$rootScope');
    var result = compile(elem)(rootScope);
    // When outside of AngularJS you need to call digest
    // rootScope.$digest();
}

请参阅:http://codepen.io/skarllot/pen/LVKpgd

答案 1 :(得分:1)

您没有提及您是否查看过之前提出的问题。我找到了两个看起来可以解决你问的问题:

How to bind an AngularJS controller to dynamically added HTML?

{{3}}