关于angular中函数的先后执行之我见,以及angular的小bug

在js中,函数的先后执行

(1)在angular中假设有这个场景,对表单资料进行编辑,刚好这个表单有select选项需要从后台中获取,这个时候这个表单使用angular进行开发的时候的正确打开方式应该是

先加载select选项,在加载表单的对应内容(由于http是异步的,并不是单纯的把js顺序调整一下就可以的)

这时候可以使用angular自带的$q返回promise来控制函数运行,

如果函数中没有其他的异步,简单粗暴的使用$timeout来控制

(2)input【type=hidden】使用ng-model无法赋值中这个bug,可以套个div把东西隐藏 type设为别的值,后者任何隐藏他的方法。

(3)在查阅资料的时候发现了大家另一种的判断list加载到最后一条的方案

angular中判断 ng-repeat是否迭代完毕。

by:古德God http://www.cnblogs.com/wangmeijian/p/5141266.html

//方法一

$scope.data = [
    {
        str: 'a'
    },
    {
        str: 'b'
    },
    {
        str: 'c'
    }
]
//自定义指令repeatFinish   
app.directive('repeatFinish',function(){
    return {
        link: function(scope,element,attr){
            console.log(scope.$index)
            if(scope.$last == true){
                console.log('ng-repeat执行完毕')
            }
        }
    }
})
<div >
    <span ng-repeat="item in data" repeat-finish>{{item.str}}</span>  //小驼峰,repeatFinish ,用 -  隔开,repeat-finish  
</div>
<div >
    <span ng-repeat="item in data" repeat-finish="renderFinish()">{{item.str}}</span>
</div>
再通过指令的attr参数获取这个处理函数

复制代码
app.directive('repeatFinish',function(){
    return {
        link: function(scope,element,attr){
            console.log(scope.$index)
            if(scope.$last == true){
                console.log('ng-repeat执行完毕')
                scope.$eval( attr.repeatFinish )
            }
        }
    }
})
//controller里对应的处理函数
$scope.renderFinish = function(){
    console.log('渲染完之后的操作')
}
app.directive('repeatFinish',function(){
    return {
        link: function(scope,element,attr){
            console.log(scope.$index)
            if(scope.$last == true){
                console.log('ng-repeat执行完毕')
                //向父控制器传递事件
                scope.$emit('to-parent');
                //向子控制器传递事件
                scope.$broadcast('to-child');
            }
        }
    }
})
//父控制器中监听事件
$scope.$on('to-parent',function(){
    //父控制器执行操作
})

//子控制器中监听事件
$scope.$on('to-child',function(){
    //子控制器执行操作
})
复制代码