列举你所知道的angular指令(不少于10个)
- ng-bind
- ng-model
- ng-app
- ng-controller
- ng-init
- ng-repeat
- ng-hide
- ng-show
- ng-if
- ng-keydown
请写出一个双向数据绑定的例子
html:
<div ng-app="myApp" ng-controller="myCtrl">
<input type="text" ng-model="name">
<p>hello {{ name }}</p>
</div>
js:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "zhangsan";
});
请列举写出angular的事件绑定,要求事件触发时会有相应的方法执行
<body ng-app="myApp" ng-controller="myCtrl">
<button ng-click="handler()"></button>
<p ng-show="isShow">隐藏/显示</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.isShow = true;
$scope.handler = function () {
$scope.isShow = !$scope.isShow;
}
});
</script>
</body>
请举例写出angular自定义指令的方法
var app = angular.module('myApp', []);
app.directive('helloWorld', function () {
return (
template: '<h1>自定义指令</h1>'
);
});
请举例写出angular发请求的方法(如,发请求到http://localhost:8080/req),并写出返回的数据怎么得到
var app = angular.module('myCtrl', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.users = [];
$http({
method: 'GET'.
url: 'http://localhost:8080/req',
}).then(function (res) {
// 成功的回调
$scope.users = res.data;
console.log(res.data);
}, function (err) {
// 失败的回调
console.log(err);
});
});
}
ng-show/ng-hide 与 ng-if 的区别?
ng-show/ng-hide: 显示或者隐藏HTML元素。
ng-if: 如果条件为false移除HTML元素,如果条件为true,会添加移除元素,并显示。
两者之间最大的区别就是ng-hide是隐藏而ng-if是对DOM进行移除
解释下什么事 rootScope以及和 scope 的区别?
scope是angularJS中作用域(其实就是存储数据的地方),很类似javascript的原型链。搜索的时候,
优先找自己的scope,如果没有找到就沿着作用域链向上搜索,直至到达根作用域rootScope。
rootScope是由angularJS加载模块的时候自动创建的,每个模块只会有1个rootScope。rootScope创建好会以拂去的形式加入到
injector中。也就是说通过
injector.get(‘
rootScope’);能够获取到某个
模块的根作用域。更准确的来说,$rootScope是由angularJS的核心模块ng创建的。
scope是html和单个controller之间的桥梁,数据绑定就靠它了。rootScope是各个controller中
scope的桥梁。用rootScope定义的值,可以在各个controller中使用。
Angular Directive中restrict 中分别可以怎样设置?
restrict中可以分别设置:
A 匹配属性
E 匹配标签
C 匹配Class
M 匹配注释
AECM 混合匹配
ng-click中写的表达式,能使用JS原生对象上的方法吗?为什么?如果不能该如何实现?
不能使用,首先它们两个的作用域是不同,ng-click的作用域是在Angular特有的控制器内的,angular的所有的方法和属性都在控制器中的$scope中,而原生的作用域是全局的。
如何实现:我们可以在ng-click表达式中调用$scope存在的方法名,然后再改方法名中可以调用JS原生对象的方法。
举例说明:
<div app="myApp" controller="myCtrl">
<p ng-click="handler()">找你零钱:{{ money }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.money = 3.33;
$scope.handler = function () {
// 这里使用JS原生的parseInt()方法
return parseInt($scope.money);
}
});
</script>
angular中的$http是什么,有什么特点?
http是AngularJS中的一个核心服务,用于读取远程服务器的数据。(类似jquery的 .ajax的对象)
特点:
可以在响应返回时用then方法来处理回调。如果使用then方法,会得到一个特殊的参数,
它代表了相应对象的成功或失败信息,还可以接受两个可选的函数作为参数。或者可以使用success和error回调代替。