Angularjs使用中的一些注意事项


1、HTML段的根元素不唯一

myModule.directive('myDirective', function factory() {
return {
  ...
  replace: true,
  templateUrl: 'someUrl'
  ...
}
});

在templateUrl属性中指定的的someUrl页面必须具有唯一根元素,如下:

<div><b>Hello</b> World!</div>

如下是一个非法的例子:

<b>Hello</b> World!

最需要注意的就是如下的代码段:

<div class='container'>
<div class='wrapper>
   ...
</div> <!-- wrapper -->
</div> <!-- container -->

注释 <!-- container --> 也会被当成第二个根节点的,所以如上也是一个非法的代码段.

2、表单的验证提示不管用(仅代表个人看法)

 <input type="text" class="form-control" placeholder="text" name="mtext"
                                       ng-required="true" ng-minlength="2"  ng-maxlength="15"
                                       ng-model="businessManager.newPageUrlAdapter.loginname" />
可能会出现如下问题:

(1)没有写ng-required="true",导致不对最小和最大长度进行检查

(2)type="text" 属性写到了后面


3、使用setTimeout()改变属性值时不起作用

代码段如下:

<p class="status-message" ng-show="message">{{ message }}</p>
$scope.message = 'Changes saved!';
setTimout(function() {
  $scope.message = null;
}, 5 * 1000);
对message值进行更新,但是不起作用。原因就是这个函数不对脏数据进行检查,所以还需要调用 $scope.$apply()  。而使用angularjs提供的$timeout时,则不用进行脏检查,因为这个函数内部已经调用过$apply方法了,正确的用法如下:

function MyController($scope, $timeout) {
  ...
  $scope.message = 'Changes saved!'; 
  $timeout(function() {
    $scope.message = null;
  }, 5 * 1000);
}

4、js、angularjs是预编译执行而不是顺序执行


var url = 'ssp/apply/'+$scope.curuser.id+'?crmbaseinfoid='+ $scope.region;
$scope.submit = function(){
    var type = 1;
    // 使用restangular发送一个url请求,相当于$http发送请求
    restangular.all(url).post().then(function(data){

    });
}
如上代码段有可能造成$scope.region、$scope.curuser.id为undefined。因为JS是先前编译的代码,所以如果将url写入外部,则先前已经编译好了,正确的写法如下:
$scope.submit = function(){
			var type = 1;
			restangular.all('ssp/apply/'+$scope.curuser.id+'?crmbaseinfoid='+ $scope.region).post().then(function(data){

			});
}

5、整数与字符串

 <input choose type="radio" ng-model="rule.num" name="choose" value=1 />

如上的写法value为1,而如果写成value="1",则类型为字符串


6、代码报错:[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify uniq


  1.       
  2. <div ng-init="words = ['高校','高校','高校']" ng-repeat="word in words">  
  3.     {{word}}  
  4. </div>  

[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys

  发现是因为相同的内容重复引起,解决方案


  1. <div ng-init="words = ['高校','高校','高校']" ng-repeat="word in words track by $index">  
  2.     {{word}}  
  3. </div>  




发布了167 篇原创文章 · 获赞 321 · 访问量 58万+


  1.       
  2. <div ng-init="words = ['高校','高校','高校']" ng-repeat="word in words">  
  3.     {{word}}  
  4. </div>  

[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys

  发现是因为相同的内容重复引起,解决方案


  1. <div ng-init="words = ['高校','高校','高校']" ng-repeat="word in words track by $index">  
  2.     {{word}}  
  3. </div>  

猜你喜欢

转载自blog.csdn.net/mazhimazh/article/details/39925653