如何在不使用ng-controller的情况下手动将控制器添加到AngularJS中的元素?

时间:2014-02-08 21:09:54

标签: angularjs

我想做点什么:

bindACustomControllerToThisElement($('#putControllerHereWithoutDirective'), function($scope){
  $scope.title = "Hello World!";
});

你可能想知道,“为什么?”好。它正在将遗留代码转换为角度。还不能完全使用标准的AngularJS方式。

2 个答案:

答案 0 :(得分:1)

如果你想要你在这里做的正是:

function bindACustomControllerToThisElement(elem,ctrlName,ctrl,deps){
  var name = elem.id || elem.attr && elem.attr('id') || false;
  if(!name) return false;
  angular.module(name,deps || []).directive('has'+ctrlName,function(){
    return {
      restrict:'C',
      controller: ctrlName
    };
  }).controller(ctrlName,ctrl);
  angular.bootstrap(elem,[name]);
}

//calling it...

var elem = document.getElementById('myAngularSection');

bindACustomControllerToThisElement(elem,'MyCtrl',function($scope){
    $scope.model = {
      message: 'Hello World'
    };
  }
);

plunker

尝试在此设置中共享数据可能会变得很复杂但是如果您在其他位置使用命名空间数据,则只需要绑定。我认为这应该有用。

答案 1 :(得分:1)

使用指令非常简单:

<!DOCTYPE html>
<html data-ng-app="app">
    <head>
        <title>Upload</title>
    </head>
    <body>
        <div id="putControllerHereWithoutDirective" data-mytest>
            {{test}}
        </div>  

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
        <script>
            'use strict';

            angular.module('app',[])

                .directive("mytest", function () {
                return {
                    restrict: 'A',
                    controller: function ($scope) {
                        $scope.test = 'mytest';
                    },
                    link: function (scope, el, attrs) {

                    function test() {
                        alert('Clicked');

                    }
                    el.on('click', test);
                }
                };
            });
       </script>
    </body>
</html>

with bind(酷:))

<!DOCTYPE html>
<html data-ng-app="app">
    <head>
        <title>Upload</title>
    </head>
    <body>
        <div id="putControllerHereWithoutDirective">
            {{test}}
        </div>  
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
        <script>
            'use strict';
            angular.module('app',[])
            .run( function($rootScope) {
                var returnFn  = angular.bind($('#putControllerHereWithoutDirective'),function(){
                    this.attr('data-ng-controller','myCtrl');
                }, []);
                returnFn();
            })
            .controller('myCtrl',function($scope){
                $scope.test = 'My test';
            })



       </script>
    </body>
</html>