[Angular] Service facotry(), custom filter

HTML: Call the funciton on the scope and give the data as param.

<!DOCTYPE html>
<html>
    <head>
        <title>Angular Binding</title>
        <script src="angular.min.js"></script>
        <script src="main.js"></script>
        <!--<link rel="stylesheet" href="css.css" />-->
    </head>
    <body>
        <div ng-app="myApp">

            <div ng-controller="FirstCtrl">
                <input type="text" ng-model="msg.message" />
                <h1>{{msg.message}}</h1>
            </div>
            
            
            <div ng-controller="SecondCtrl">
                <input type="text" ng-model="msg.message" />
                <h1>{{reverseMessage(msg.message)}}</h1>
            </div>
        </div>    
    </body>
</html>

Javascript: Define a method on scope and receive a param.

var app = angular.module('myApp', []);
app.factory('DataFromService', function(){
    return {message: "This is from service"}
});

function FirstCtrl($scope, DataFromService){
 /*DataFromService: Object {message: "This is from service", reply: "I am Zhentian"} */
    $scope.msg = DataFromService;
}

function SecondCtrl($scope,DataFromService){
    $scope.msg = DataFromService;
    
    $scope.reverseMessage = function(message){
        return message.split(" ").reverse().join(" ");
    };
}

 

-------------------------------Custom Filter-----------------------

But using function is not good enough, we can use filter to do this.

We can define customer filter:

app.filter('reverse', function(DataFromService){
    return function(text){
        return text.split(" ").reverse().join(" ");
    }
});
            <div ng-controller="SecondCtrl">
                <input type="text" ng-model="msg.message" />
                <h1>{{msg.message | reverse}}</h1>
            </div>

 

posted @ 2014-08-11 16:07  Zhentiw  阅读(286)  评论(0编辑  收藏  举报