美文网首页
AngularJS学习笔记

AngularJS学习笔记

作者: 段誉九段 | 来源:发表于2017-08-14 09:52 被阅读0次

    引入angular.js

    若在页面中引入了angular.js并添加了ng-app="app" ng-controller="ctrl",而没有实现模型,会报错:

    Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
    Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
    

    初始化变量

    • 方法一,在html中设置
    <div ng-app="" ng-init="firstName='John'">   
        <p>姓名为 <span ng-bind="firstName"></span></p>     
    </div>
    
    • 方法二:在js中设置
    var app = angular.module('app', ['ngAnimate']);
    app.controller('ctrl', function ($scope, $http) {
        $scope.step = 1;
        ...
    });
    

    防止载入过程中界面闪烁

    添加属性:ng-cloak

    <div class="mask" ng-show="show" ng-cloak>
    

    IntelliJ不识别AngularJS、无自动提示的问题

    • 问题描述:
      html文件中提示 Attribute ng-disabled is not allowed here,js文件中不识别angular.module('myApp', [])方法;
      代码自动完成的提示不完整。
    • 解决:
      办法一:在工程中放入angular.js,而不仅仅是angular.min.js,无论引用哪一个
      办法二: 设置 > Languages & Frameworks > JavaScript > Libraries. Attach the local angular.js as a file in the new library.

    使用http请求时,需声明使用http模块,否则会提示$http is not defined,其他模块类似

    app.controller('ctrl', function ($scope, $http) {
        $scope.getX = function () {
            $http({
                method: 'GET',
                url: 'json/x.json'
            }).then(function success(response) {
                var status = response.data.status;
                ...
            }, function error(e) {
                console.log(e);
            });
        };
    });
    

    一个html页面只能加载一个ng-app的问题

    1. 可以简单的将多个 ng-app 合并成为一个根模块。
    2. 可以手动装载除了第一个以外的多个 ng-app。
      angular.bootstrap(document.getElementById("app2div"), ['myApp2']);

    AngularJS操作cookie

        var app = angular.module('myApp', ['ngCookies']);
        app.controller('myCtrl', function ($scope, $http, $cookies) {
            $scope.foo = function () {
                $cookies.put('user', 'eric', {path: '/'});
            };
        });
    

    注意:
    一、默认情况下子目录下设置的cookie父目录页面读不到,需明确设置path
    二、不要将$cookies写成$cookieStore

    文档加载完成时执行

        $scope.$watch('$viewContentLoaded', function () {
            $scope.init();
        });
    

    相关文章

      网友评论

          本文标题:AngularJS学习笔记

          本文链接:https://www.haomeiwen.com/subject/qallrxtx.html