用angularjs遇到的坑

本文分享了AngularJS开发过程中的实用技巧,包括双向绑定、条件渲染、指令通信、按需加载等方面的经验总结,并提供了常见问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.

双向绑定的指令,如果用ng-if去控制它的显示和隐藏。那么base 的controller中取不到值$scope.val

用ng-show控制,取值ok


2.

ng-class控制的判断条件,如果是string变量和一个boolean变量做与和或的操作

可能会出现判断不生效,这个时候可以将string变量强转为boolean变量


3.

指令中子scope和父scope的通信,可以通过

scope: {

& = @

}


4.

双向绑定的数据可能会出现数据刷新,但是dom渲染没有同步刷新的情况

可以通过$scope.$apply来手动通知页面update绑定的数据的。

文章: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html


5.

js按需加载,首先在$routeProvider里面加resolve属性

$routeProvider.
        when('/phones', {
               templateUrl: 'partials/phone-list.html', 
               controller: PhoneListCtrl, 
               resolve: PhoneListCtrl.resolve})

function PhoneListCtrl($scope) {
  //本身不用管,该怎么弄怎么弄
}

PhoneListCtrl.resolve = {
  delay: function($q) {
    var delay = $q.defer(),
    load = function(){
        $.getScript('/js/xxxxx.js',function(){
        delay.resolve();
        });
    };
    load();
    return delay.promise;
  }
}



others

1. templateURL和路由之类的要在web server下运行。

2. 使用模板replace设为true,模板里也要有相应的标签,否则不出现任何数据。

3. 1.2版本之后,ngRoute模块独立。

4.空的controller不定义会出错。

5.Directive的link参数是有顺序的:scope,element,attrs,ctrl

6.ng-repeat不能循环重复的对象。hack: ng-repeat="thing in things track by $id($index)"

7.尽量更新的是变量的属性而不是单个变量本身。

8.注意ng-repeat,ng-controller等会产生独立作用域。

9.当jquery载入,则使用jquery,否则使用内置jqlite。all element references in Angular are always wrapped with jQuery or jqLite; they are never raw DOM references.

10.Uncaught Error: [$location:ihshprfx]  A标签没有去掉 <a href="#" ng-click="someMethod();"></a>

11.Error: listen EACCES 当在linux下,会出现这个错误,因为你监听的端口的原因,这里我的是33。把它改成8080或3030之类大的端口数就可以了。有一个规定,这些端口最好是大于1024。

12. select在没有ng-model的时候,无法显示。同理,当遇到无法显示最好看文档少了什么。

补:当ng-options的源,跟书写不相配时会出现全部选择的情况,如下:

var a = [{"id":1,"name":"Ryan"}....] ,ng-options="item.i as item.name for item in a"  // i与id不同

----------------------------------------------------------------------------------------

13.ng-bind-html-unsafe已去除,可以用['ngSanitize'] 模块或使用$sce服务

From stackoverflow

You indicated that you're using Angular 1.2.0... as one of the other comments indicated, ng-bind-html-unsafe has been deprecated.

Instead, you'll want to do something like this:

<div ng-bind-html="preview_data.preview.embed.htmlSafe"></div>

In your controller, inject the $sce service, and mark the HTML as "trusted":

myApp.controller('myCtrl', ['$scope', '$sce', function($scope, $sce) { // ... $scope.preview_data.preview.embed.htmlSafe = $sce.trustAsHtml(preview_data.preview.embed.html); }

Note that you'll want to be using 1.2.0-rc3 or newer. (They fixed a bug in rc3 that prevented "watchers" from working properly on trusted HTML.)






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值