angularjs 权威指南 版本 1.2.6

时间:2022-06-29 17:47:08

1 $rootScope  run  : run 方法初始化全局的数据 ,只对全局作用域起作用 如$rootScope

<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<div ng-app="a" >
{{name}}
</div>
<script>
var app=angular.module('a',[]);
    app.run(function ($rootScope) {
        $rootScope.name='sdfa';
    });
</script>

2 $parse 将一个AngularJS表达式转换成一个函数

<script src="http://apps.bdimg.com/libs/angular.js/1.2.6/angular.min.js"></script>
<div ng-app="a" ng-controller="ctrl" >
{{ParsedValue}}
</div>
<script>
    /*
    * $parse 将一个AngularJS表达式转换成一个函数
    *$parse服务根据$scope.context中提供的上下文解析$scope.expression语句,然后使用$scope.data数据填充表达式中的变量
    * */
var app=angular.module('a',[]);
    app.controller('ctrl',function ($scope,$parse) {
       $scope.context={
           add: function (a,b) {return a+b+1;},
           mul: function(a,b){return a*b;}
       }
        $scope.expression="mul(a,add(b,c))";
        $scope.data={
            a:3,
            b:6,
            c:9
        }
        var parseFunc=$parse($scope.expression);
        $scope.ParsedValue=parseFunc($scope.context,$scope.data);
    });
</script>

demo2 :输入表达式  1+2*3 结果为7

<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<div ng-app="a" ng-controller="ctrl" >
    <input type="text" ng-model="expression">
{{ParsedValue}}
</div>
<script>
var app=angular.module('a',[]);
    app.controller('ctrl',function ($scope,$parse) {
        $scope.$watch("expression", function (newValue,oldValue,context) {
            if(newValue!== oldValue){
                var parseFunc=$parse(newValue);
                $scope.ParsedValue=parseFunc(context);
            }
        })
    });
</script>

3. ng-message表单验证

<!DOCTYPE html>
<html ng-app="myTest">
<head>
    <title>Index</title>
    <script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script>
    <script src="//cdn.bootcss.com/angular-messages/1.5.7/angular-messages.js"></script>
</head>
<body>
    <form name="myForm" class="form-horizontal" novalidate>
                用户名<input type="text" placeholder="ng-Messages" name="name" ng-model="username"
                       ng-minlength=3 ng-maxlength=20 required />
                <hr/>
                $error:{{myForm.name.$error}}
                <hr/>
                <div ng-messages="myForm.name.$error">
                    <div ng-message="required">这是必填项</div>
                    <div ng-message="minlength">字符太短小于3</div>
                    <div ng-message="maxlength">字符太长大于20</div>
                </div>
    </form>
</body>
</html>
<script>
    angular.module("myTest", ['ngMessages']);
</script>