javascript 如何将 jQuery 代码转换为可用的 AngularJS 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26375099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:53:21  来源:igfitidea点击:

How to convert jQuery code into usable AngularJS code

javascriptjqueryangularjscontrollerdirective

提问by codenaugh

I am new to AngularJS and would like to create functionality for a login page similar to what you find here when you click the 'Forgot Password' link:

我是 AngularJS 的新手,想为登录页面创建类似于单击“忘记密码”链接时在此处找到的功能:

http://bootsnipp.com/snippets/featured/login-amp-password-reminder#comments

http://bootsnipp.com/snippets/featured/login-amp-password-reminder#comments

Is it best to use a directive, since this is behavioral, instead of a controller? I've tried quite a bit with creating a controller for it, but as I search for help on the subject I find that using a controller for this may not be the way to go. Here was my latest trials which was unsuccessful (the link does nothing when clicked):

最好使用指令,因为这是行为,而不是控制器?我已经尝试了很多为它创建控制器,但是当我搜索有关该主题的帮助时,我发现为此使用控制器可能不是要走的路。这是我最近未成功的试验(点击链接时什么也不做):

on controller side in a js file:

在 js 文件中的控制器端:

angular.module('mean.users')
    .controller('SwitcherCtrl', ['$document',
        function($document) {
        $document.ready(function () {
            $document.getElementById('olvidado').click(function (e) {
                e.preventDefault();
                $document.getElementById('form-olvidado').toggle('500');
            });
            $document.getElementById('acceso').click(function (e) {
                e.preventDefault();
                $document.getElementById('form-olvidado').toggle('500');
            });
        });
    }
])

on html side, I included ng-controller="SwitcherCtrl" where necessary.

在 html 方面,我在必要时包含了 ng-controller="SwitcherCtrl"。

采纳答案by codenaugh

Thanks to everyone who answered. They kicked off this thing moving in the right direction and I was able to improve upon it to come to the exact answer shown below.

感谢所有回答的人。他们开始朝着正确的方向发展,我能够对其进行改进以得出如下所示的确切答案。

The HTML:

HTML:

<div ng-controller="SwitcherCtrl">
    <div data-fold-toggle="active">
        <form id="login">
            <input type="email" ng-model="email" required="">
            <input type="password" ng-model="password" required="">
            <button type="submit">Login</button>
            <a ng-click="active=!active">Forgot your password?</a>
        </form>
    </div>
    <div data-fold-toggle="active" style="display: none;">
        <form id="forgotpw">
            <input type="email" ng-model="email" required="">
            <button type="submit">Reset Password</button>
            <a ng-click="active=!active">Account Access</a>
        </form>
    </div>
</div>

The Controller & Directive:

控制器和指令:

.controller('SwitcherCtrl', function($scope) {
    $scope.active = true;
})
.directive('foldToggle', function() {
    return {
        restrict: 'A',
        scope:{
            isOpen: '=foldToggle'
        },
        link: function(scope, element) {

            scope.$watch('isOpen', function(newVal,oldVal){
                if(newVal !== oldVal){
                    element.toggle(200);
                }
            });
        }
    };
});

回答by Michail Michailidis

JQuery approach is completely incompatible with AngularJS. DOM Manipulation is only allowed in directives in the link function otherwise it is a very bad practice. Try to start from scratch and forget about JQuery. The magic of AngularJS happens with 2-way bindings.

JQuery 方法与 AngularJS 完全不兼容。DOM 操作只允许在链接函数中的指令中使用,否则这是一种非常糟糕的做法。尝试从头开始,忘记 JQuery。AngularJS 的神奇之处在于 2 路绑定。

You could use a directive, with a login controller and a factory/service to hold the username and password and send it to the database. For this login there is definitely no need for JQuery at all. You can check this question here: AngularJS- Login and Authentication in each route and controller

您可以使用带有登录控制器和工厂/服务的指令来保存用户名和密码并将其发送到数据库。对于此登录,完全不需要 JQuery。你可以在这里检查这个问题: AngularJS- Login and Authentication in each route and controller

edit:In your question above, it is not a directive instead of a controller. A directive can have a controller that is applied to a specific scope. You could do the same thing with both but depends how many times you will reuse this login snippet - I guess you won't need it but I believe it is still good practice to make one.

编辑:在你上面的问题中,它不是指令而不是控制器。指令可以有一个应用于特定范围的控制器。你可以对两者做同样的事情,但取决于你将重复使用这个登录片段的次数 - 我想你不会需要它,但我相信制作一个仍然是一个好习惯。

edit 2:if you havent' read this one, please do it! I believe you will answer most of your questions about the two different (opposite I would say) technologies. "Thinking in AngularJS" if I have a jQuery background?Also since I came from Jquery background too, I followed these four resources in order and now I can make most of the things I want:

编辑 2:如果你还没有读过这个,请读一读!我相信您会回答关于这两种不同(与我所说的相反)技术的大部分问题。如果我有 jQuery 背景,“在 AngularJS 中思考”?另外因为我也有 Jquery 背景,所以我按顺序关注了这四个资源,现在我可以制作大部分我想要的东西:

edit 3:Since I saw good interest in my answer I decided to expand it with what to avoid/best practices so the code is more testable, maintainable and easier to migrate to Angular 2:

编辑 3:因为我对我的答案很感兴趣,所以我决定用要避免的/最佳实践来扩展它,以便代码更易于测试、可维护并且更容易迁移到 Angular 2:

回答by Gabs00

You can try this out, it uses directives and html. Whether the login or forgot username shows is tied to the state of a scope variable in the directives link function.

你可以试试这个,它使用指令和 html。登录或忘记用户名的显示与指令链接函数中作用域变量的状态有关。

Fiddle

小提琴

<div ng-app="myApp">

    <div my-auth>

        <div ng-show="active">
            <form name="login">
                <input type="email" ng-model="email" placeholder="[email protected]" required />
                <input type="password" ng-model="passwd" required />
                <button ng-disabled="!login.$valid">Login</button>
            </form>
            <a href="#" ng-click="toggle()">forgot password?</a>
        </div>

        <div ng-show="!active">
            <form name="forgot">
                <input type="email" ng-model="email" placeholder="[email protected]" required />
                <button ng-disabled="!forgot.$valid">Reset Password</button>
            </form>
            <a href="#" ng-click="toggle()">access</a>
        </div>
    </div>
</div> 

The directive

该指令

angular.module('myApp', [])
.directive('myAuth', function(){
    return {
        link: function(scope, elem, attr){
           scope.active = true;
           scope.toggle = function(){
               scope.active = !scope.active;
           };
        }
    };
});