2014-02-08 15 views
3

我想這樣做:如何在不使用ng-controller的情況下手動將控制器添加到AngularJS中的元素?

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

你可能會問,「爲什麼?」好。它將遺留代碼轉化爲角色。不能完全使用AngularJS的標準方式。

+1

我不知道它是否適合yourneeds但它是我認爲無鍋的第一件事:) http://docs.angularjs.org/api/angular.bind關於第二個想法,如果你可以把手放在標記上可能是一個指示是要走的路 – Whisher

+0

@Whisher我會怎麼做呢?你可以使用'bind'和''directive'來編寫一些示例代碼嗎? –

回答

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

隨着指令很簡單:

<!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> 

與綁定(酷:))

<!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> 
相關問題