Angularjs:获取控制器中的元素

时间:2014-01-23 14:46:05

标签: javascript angularjs

我是angularjs的新手,我知道$scope表示控制器和视图之间的连接,但除了寻找class="ng-scope"获取范围元素之外还有其他方法,我的意思是的是:

function someControllerFunc($scope){
       $scope.element;
}

我知道同一个控制器可以分配给多个范围,所以也许这是不可能的。

4 个答案:

答案 0 :(得分:63)

您可以将元素传递给控制器​​,就像作用域一样:

function someControllerFunc($scope, $element){

}

答案 1 :(得分:11)

$element$compileProvider提供给$controllerProvider的四个本地人之一,然后被提供给$injector。只有在被要求时,进样器才会在控制器功能中注入本机。

四个当地人是:

  • $scope
  • $element
  • $attrs
  • $transclude

官方文件:AngularJS $compile Service API Reference - controller

来自Github angular.js/compile.js的源代码:

 function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
    var elementControllers = createMap();
    for (var controllerKey in controllerDirectives) {
      var directive = controllerDirectives[controllerKey];
      var locals = {
        $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
        $element: $element,
        $attrs: attrs,
        $transclude: transcludeFn
      };

      var controller = directive.controller;
      if (controller == '@') {
        controller = attrs[directive.name];
      }

      var controllerInstance = $controller(controller, locals, true, directive.controllerAs);

答案 2 :(得分:2)

我不知道你究竟是什么意思,但希望它对你有所帮助 通过此指令,您可以访问控制器内的DOM元素 这个示例可以帮助您将元素集中在控制器

.directive('scopeElement', function () {
    return {
        restrict:"A", // E-Element A-Attribute C-Class M-Comments
        replace: false,
        link: function($scope, elem, attrs) {
            $scope[attrs.scopeElement] = elem[0];
        }
    };
})

现在,在HTML中

<input scope-element="txtMessage" >

然后,在控制器内部:

.controller('messageController', ['$scope', function ($scope) {
    $scope.txtMessage.focus();
}])

答案 3 :(得分:0)

创建自定义指令

<div ng-render-callback="fnRenderCarousel('carouselA')" ng-el="carouselA"></div>

html模板的代码

$scope.fnRenderCarousel = function(elName){
    $($scope[elName]).carousel();
}

控制器功能

public void actionPerformed(ActionEvent arg0) {
                try {
                    String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";

                    Pattern pattern = Pattern.compile(USERNAME_PATTERN);
                    Matcher regexMatcher = pattern.matcher(uname.getText());

                    if (!regexMatcher.matches()) {
                        JOptionPane.showMessageDialog(null, "Login Success");
                        travel launch = new travel();
                    } else {
                        JOptionPane.showMessageDialog(null, "Username / Password is Wrong");
                    }
                } catch (Exception e) {
                    System.out.println(e);