Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

angularjs指令--指令创建 #1

Open
msforest opened this issue Dec 26, 2016 · 1 comment
Open

angularjs指令--指令创建 #1

msforest opened this issue Dec 26, 2016 · 1 comment
Labels
javascript 跟js相关的笔记

Comments

@msforest
Copy link
Owner

msforest commented Dec 26, 2016

指令(Directives)是所有AngularJS应用最重要的部分。尽管AngularJS已经提供了非常丰富的指令,但还是经常需要创建应用特定的指令。

自定义指令

指令可以有四种表现形式,分别为元素(element)、属性(attribute)、注释(comment)、样式类(class),正好代表ECMAScript的前四个字母,还是很好记的。基本样式如下:

var app = angular.module('myapp', []);
 
app.directive('helloWorld', function() {
  return {
      restrict: 'ECMA',
      replace: true,
      transclude: true,
      template: '<div>Hello World!!</div>'
      //templateUrl: 'hello.html'
  };
});

使用app.directive()方法在模块中注册一个新的指令,第一个参数是指令的名称,第二个参数是返回指令定义对象的函数;如果你的指令依赖于其他的对象或者服务,比如 $rootScope, $http, 或者$compile,他们可以在这个时间被注入。
页面使用形式:

<hello-world></hello-world>
<div class="hello-world"></div>
<!-- directive:hello-world -->
<div hello-world></div>

部分属性说明:

  • restrict: 用来声明指令在DOM中以何种方式被声明,默认值是A
  • replace: 默认值为false,意思是模板会被当做子元素插入到调用此指令的元素内部
  • transclude: 为true,表示允许将自己的html模板嵌入到指令模板中,默认值为false
  • template: html文本,展示在页面渲染的内容
  • templateUrl: 外部html文件路径,在实际生产中,可以提前将模板缓存到一个定义模板的javascript文件中。

angularjs深度学习参考


Adventure may hurt you, but monotony will kill you. - -也许冒险会让你受伤,但一成不变会使你灭亡。

@msforest msforest changed the title angular指令(1) angular指令--指令创建 Jun 19, 2017
@msforest msforest changed the title angular指令--指令创建 angularjs指令--指令创建 Jun 19, 2017
@msforest
Copy link
Owner Author

msforest commented Jun 19, 2017

29 AngularJS Interview Questions – Can You Answer Them All?

1. 对angular的filter过滤器进行单元测试的基本步骤?

  • 注入包含filter的模块
  • 加载filter依赖的mocks相关js
  • 获取filter实例去使用$filter('filtername')
  • 编写预期的结果

2.watches存放最大的数量是多少,怎么保持一个可观的数量?

  • 为了减少内存消耗和提升性能,应该限制watches数量在2000以内;使用ng-stats插件可以帮助跟踪watches的数量和digest循环。

3.控制器之间怎么传递数据?

  • 创建services,利用services进行数据传递
  • 使用events传递($emit/$broadcast)
  • 使用$rootScope传递
  • 使用$parent/nextSibling/controllerAs传递

4.ng-ifng-show/ng-hide的不同?

  • ng-show/ng-hide总是会插入到DOM中,通过条件判断来决定display的属性值显示与否;ng-if根据条件判断是否插入到DOM中;当我们判断是否显示DOM的时候,用ng-if总是比ng-show/ng-hide效果好。

5.AngularJS的digest循环是什么?

  • 每一次的digest的循环,AngularJS会对scope数据值进行新老值的比较;digest循环是自动触发的,也可以通过$apply手动触发digest循环。
    For more information, take a look in the ng-book explanation: The Digest Loop and $apply

6.使用AngularJS在哪儿实现DOM操作?

  • 指令。DOM操作不应该出现控制器、服务、或其他地方。
    Here is a detailed explanation

7.混合使用AngularJS和jQuery好还是不好?

  • 肯定是不好的。我们应该远离jQuery,AngularJS有和jQuery类似的方法去操作DOM

8.如果要从1.4迁移到1.5,主要重构的事情是什么?

  • directivecomponent适配成1.5的components

9.怎么实现单向绑定

  • {{::value}}

10.单向绑定和双向绑定有什么区别

11.解释一下$scope.$apply()是怎么工作的?

  • $scope.$apply()是AngularJS的一个核心方法,强制angular引擎运行所有watch上的变量。

12.使用什么指令可以通过移除DOM上的元素而不改变样式来隐藏元素?

  • ng-if

13.什么使得angular.copy()如此强大?

  • 变量的深拷贝

14. 怎样使AngularJS的services返回一个promise?

angular.factory('testService', function($q){
	return {
		getName: function(){
			var deferred = $q.defer();

			//API call here that returns data
			testAPI.getName().then(function(name){
				deferred.resolve(name)
			});
			return deferred.promise;
		}
	}
});

15.略

16. 指令的类型都有哪些?如何使用?

  • 创建指令的时候,使用restrict来指定指令的类型:A/E/C/M

17.什么时候使用属性?什么时候使用元素?

  • 创建component时使用元素,装饰或添加新功能使用属性。

18.如何重置$timeout/$interval,如何取消$watch

var customTimeout = $timeout(function () {
  // arbitrary code
}, 55);

$timeout.cancel(customTimeout);
///////
var deregisterWatchFn = $scope.$on(‘$destroy’, function () {
    // we invoke that deregistration function, to disable the watch
    deregisterWatchFn();
});

19.解释$scope是什么?

  • Scope是js对象,是表达式的执行上下文;Scopes被设置成层级结构,和DOM结构类似;Scope可以监测表达式和传播事件;Scope作为控制器和视图的一种桥梁。

20.指令是什么?

  • 指令是一种作为DOM元素的标记,用于指示AngularJS的$compile服务绑定特定的行为到DOM元素上,或将碎片模板转换成DOM元素。

21.DDO (Directive Definition Object)是什么?

  • DDO是创建指令的使用的一个Object对象,创建指令的对象有以下参数:
var directiveDefinitionObject = {
    priority: 0,
    template: '<div></div>', // or // function(tElement, tAttrs) { ... },
    // or
    // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
    transclude: false,
    restrict: 'A',
    templateNamespace: 'html',
    scope: false,
    controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
    controllerAs: 'stringIdentifier',
    bindToController: false,
    require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
    compile: function compile(tElement, tAttrs, transclude) {
      return {
        pre: function preLink(scope, iElement, iAttrs, controller) { ... },
        post: function postLink(scope, iElement, iAttrs, controller) { ... }
      }
      // or
      // return function postLink( ... ) { ... }
    },
    // or
    // link: {
    //  pre: function preLink(scope, iElement, iAttrs, controller) { ... },
    //  post: function postLink(scope, iElement, iAttrs, controller) { ... }
    // }
    // or
    // link: function postLink( ... ) { ... }
  };"

22. 什么是单例模式?在AngularJS中哪里使用到这种模式?

  • 使用一次或多次使用类时只实例化一次对象。在DI和services中经常使用到单例。

23. interceptor是什么?哪里使用的比较多?

  • interceptor是发起$http请求的一个中间件。interceptor是注册$httpProvider的一个工厂函数,在请求和响应的时候会调用interceptor。

24.在指令执行和转换之前,如何修改指令模板?

  • 使用compile方法。因为在执行和转换之前,compile方法有权修改指令模板,所以compile方法是安全地处理模板的。

25.如何验证文本输入值?

  • 使用ng-pattern内置指令用正则表达式匹配。

26.在应用中,如何实现全局的异常处理?

  • AngularJS提供了一个内置的错误处理服务叫$exceptionHandler
myApp.factory('$exceptionHandler', function($log, ErrorService) {
    return function(exception, cause) {
        
        if (console) {
            $log.error(exception);
            $log.error(cause);
        }

        ErrorService.send(exception, cause);
    };
});

27.通过按钮点击事件如何隐藏一个元素?

28.如何通过数据模型值的变化来触发更多的行为?

  • 使用$watch方法实现
function MyCtrl($scope) {
	$scope.email = "";

	$scope.$watch("email", function(newValue, oldValue) {
		if ($scope.email.length > 0) {
			console.log("User has started writing into email");
		}
	});
}

29.如何根据checkbox的状态来禁用按钮?

  • 使用ng-disable指令绑定到checkbox的值
<body ng-app>
	<label><input type="checkbox" ng-model="checked"/>Disable Button</label>
	<button ng-disabled="checked">Select me</button>
</body>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
javascript 跟js相关的笔记
Projects
None yet
Development

No branches or pull requests

1 participant