AngularJS 面试题

  1. Why use AngularJS
    1). It uses MVC to let you split app into MVC components, and the framework will execute your functions when needed, which means you will do much less work on the structure of the application
    2). It offers two way data binding, and dependency injection
    3). Easy to build up SPA
    4). Use POJO(Plain old JavaScript Object), does not need getters and setters, which makes your code much cleaner.
    5). Directives in AngularJS make it easier to add additional functionality into the HTML

  2. Difference between AngularJS and JQuery
    jQuery is more like a javascript library, which is a tool for developers to manipulate and control DOM elements.
    AngularJS is a JavaScript framework which has its own way of implementing things and rules. It asks you to follow the MVC pattern to split your code and it will call your functions when needed. It is more suitable for develope the web application. Definitely, you can use jQuery inside AngularJS, however, in order to keep the application code clean, you should add your jQuery code inside your angular directives instead of controllers.

  3. Scope
    Every controller has an associated $scope object. Scope is the glue to connect the View and controller.

    scope vs this:
    variables in scope can be used by its child, which means it supports inheritance.
    variables in this cannot be used by other controllers, which means all the properties in this are parallel to other controllers.

this

When the controller constructor function is called, this is the controller.
When a function defined on a $scope object is called, this is the "scope in effect when the function was called". This may (or may not!) be the $scope that the function is defined on. So, inside the function, this and $scope may not be the same.

$scope
Every controller has an associated $scope object.
A controller (constructor) function is responsible for setting model properties and functions/behaviour on its associated $scope.
Only methods defined on this $scope object (and parent scope objects, if prototypical inheritance is in play) are accessible from the HTML/view. E.g., from ng-click, filters, etc.

4. Custom Directive:

angular.module("MyApp").directive("MyDirective",,function(){
    return {
        restrict: E, (E--element, A--attribute, C--class, they can be combined as needed, eg. AEC)
        scope: {title:'@' }
        link: function(){
            //manipulate the DOM
        },
        templateUrl: ...,
        template:'<div>{{value}}</div>',
        replace: true,
    };
});
  • Three kinds of scope in the directive can be set:
    Shared scope: the directive works with the same scope that is already available for the DOM node where the directive appear(default scope, scope=false). It shares the scope with the enclosed controller, not create a new one.
    Inherited scope: scope=true, the directive inherits the scope of the controller. A new scope is created instead of using the parent scope.
    Isolated scope:if you want to set an isolated directive scope, just use scope: {} will be fine.There are 3 options to interact with the outside in the isolated directives--local scope properties:

    1. @: it is used to access string values that are defined outside the directive. Just as the example, which means if the controller set up a variable in scope as 'title', then the directive will have access to the title variable.
    2. =: In cases where you need to create a two-way data binding between the outer scope and the directive's isolate scope, you can use the '=' character. scope:{customer:'='}
    3. &: It allows the consumer of a directive to pass in a function that the directive can invoke.
  • replace:true
    replace the current element with the contents of the HTML. The replacement process migrates all of the attributes / classes from the old element to the new one.

  1. Data Binding:
    It is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and vise versa.

  2. Control oriented vs. Data oriented (Two programming style)
    Control oriented: put data in and extract data out through controls, typically makes your code complex, hard to maintain when the controls grows larger.
    data oriented: when user modifies the data, the property automatically update. A lot of unnecessary code could be eliminated with data-oriented frameworks.

  3. ng-disabled vs. html disabled
    html disabled is a boolean attribute for the element and it is not binded with other models in the JS code, however the ng-disabled could be binded with boolean variables or experssions in the AngularJS code to control the element dynamically.

8. Route:

  • It defines the route associate controller with view to load different views to our angularjs application page. It is the key component to the make the Single Page Application.
angular.model("MyApp",["ngRoute"]).config(function($routeProvider){
    $routeProvider
        .when('/',  
            {
                templateUrl:"firstPage.html",
                controller:"firstController"
            })
        .when('/home',
            {
                templateUrl:"homePage.html",
                controller:"homneController"
            })
        .otherwise(
            {redirectTo: '/'}
        );
});
  • you can also use the $routeParam service to retrieve the current set of route parameters, pass some data between different controllers.
  1. controller
    It is a brain for a view: interact with view with $scope, defines properties, functions, knows how to retrieve data from factory or services.
    Do not use Controller to:

    1. Manipulate DOM: Controllers should contain only the business logic
    2. Format input: Use angular form controls instead
    3. Share code or state across controllers: Use service instead
  2. Service, provider, factory
    Controller should be thin, all your business logic code should write in the service, provider or factory in angular application.
    Factory: when using a Factory, you create an object, add properties to it, then return that same object. When you pass this service into your controller, those propertieis on the object will now be available in that controller through your factory.

    Service: When you are using a Service, it's instantiated with the new keyword. Because of that, you will add properties to this and the service will return this. When you pass the service into your controller, those properties on this will now be available on that controller through your service.

    Providers: they are the only services you can pass into your .config() function. Use a provider when you want to provide module-wide configuration for your service object before making it available. The only properties or methods that will be available in your controller are those properties or methods which are returned from the $get() function.

    See details at: http://tylermcginnis.com/angularjs-factory-vs-service-vs-provider/

  3. Value and Constant
    Constant can be injected anywhere, the value of a constant should never be changed.
    Value differs from constant in that value can not be injected into configurations, it can be changed by reassign.

  4. $http
    Use the $http Service: $http.get("api");

  5. $watch, $digest, $apply
    $watches can be used to watch any value, and trigger a function call when that value changes. A $watch can be set up from any $scope by calling $scope.$watch(watchExpression,listener,[objectEquality]). When you create a data binding from somewhere in your view to a variable on the $scope object, AngularJS creates a "watch" internally. A watch means that AngularJS watches changes in the variable on the $scope object.
    The listener callback to be executed whenever the watchExpression changes. WatchExpression could be a value or a function that returns a value, and those value will be watched.

$scope.$watch(
        function(scope){scope.name;},
        function(newValue, oldValue){
            document.getElementById("").innerHTML = ""+newValue;
        });
    Note that use "scope" without the $ in the watch function
  • $digest, this function iterates through all watches and checks if any of the watched variables have
    changed. If a watched variable has changed, a corresponding listener function is called. The listener
    function does whatever work it needs to do, for instance changing a HTML text to reflect the new value of the watched variable. Thus, the $digest() function is what triggers the data binding to update. Most of the times, AngularJS calls it for you, in some corner cases, you may need to call $scope.$digest() yourself if you find some elements do not update.

  • $apply function is used to execute some code, and then call $scope.digest() after that, so all watches are checked and the corresponding watch listener functions are called. The apply() function is useful when integarting AngularJS with other code.

  1. $templateCache
    The first time a template is used, it is loaded in the template cache for quick retrieval. You can load templates directly into the cache in a script tag, or by consuming the $templateCache serice directly.

  2. MVVM && MVP
    MVVM-- controller replaced by view model. This view model sits below the UI layer, it exposes the data and command objects that the view needs.
    MVP-- controller replaced by presneter. The presenter sits at the same level as the view. It listens to the events of both the view and the model and mediates the interactions between both view and model.

    adv MVVM vs MVC
    1). Enable saparation of the Model and View
    2). support for automatic two-way databinding

  3. RootScope
    Each angular application has exactly one rootscope. It can access all the child scopes. It is the only place where the department property is defined.

  4. compile() and link() functions:
    compile: use for template DOM manipulation, hence manipulations that apply to all DOM clones of the template associated with the directive.
    link: use for registering DOM listeners as well as instance DOM manipulation.

  5. ng-class:
    The ngClass directive allows you to dynamically set CSS classes on an HTML element by data binding an expression that represents all classes to be added.

  6. Security:
    A cross-site scripting (XSS) refers to client-side code injection attack.

  7. Cross-site request forgery(CSRF)
    A Cross-site request forgery is that a malicious site can cause a visitor's browser to make a request to your server that causes a change on the server.

  8. Prevent CSRF
    Make sure form submissions that cause server side changes use your own forms

    1. check the referrer header.
    2. Include a hidden field in the form and check its value when the form is submitted.
  9. $scope and scope:
    They all refer to a scope. $scope is glue between controller and view, it is used to propagate date from controller to the view. $scope uses dependency injection, all these things that passed to a controller or service, are depend on the providers that are available to application. scope: angularJS just calling a method with scope object as parameters which already provided, the order of these prarmeters (scope, element, attribute) in functions is important.

  10. $resource
    With resource object, we can interact with RESTful server-side data sources. It requires the ngResource module to be installed. $resource(url,[paramDefaults],[actions],options)

  11. 3 kinds of Dependency Injection
    1).inline Array Annotation
    someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter){}]);
    2).$inject property Annotation
    var MyController = function($scope, greeter) {
    // ...
    }
    MyController.$inject = ['$scope', 'greeter'];
    someModule.controller('MyController', MyController);
    3).implicit Annotation(Minification will rename it and may break the app)
    someModule.controller('MyController', function($scope, greeter) {
    // ...
    });
    If you do not want minification to break your app, use ng-annotate in ng-strict-di
    ng-strict-di: <html ng-app="myApp" ng-strict-di>
    It throws an error whenever a service tries to use implicit annotations.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,332评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,508评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,812评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,607评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,728评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,919评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,071评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,802评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,256评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,576评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,712评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,389评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,032评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,026评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,473评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,606评论 2 350

推荐阅读更多精彩内容