重修前端

angularJS之“自定义指令”

2017-03-02  本文已影响9人  adiu

应用场景


某一个特定的功能,我们要在应用程序内或程序之间进行复用

应用模板


<directive-name data-source="data"></directive-name>
$scope.data = [
   {'name': 'adiu', 'interesting': '听音乐', 'value': 1},
   {'name': 'jack', 'interesting': '看电视', 'value': 2},
   {'name': 'jenny', 'interesting': '打篮球', 'value': 3}
]
app.module('app').directive('directiveName', function() {
    return {
        link: function(scope, element, attrs) {
            var data = scope[attrs['source']];
            if(angular.isArray(data))
            {
                angular.forEach(data, function(item) {
                    console.log(item);
                })
            }
        },
        template: '',
        restrict: 'E' 
    }
})

指定特定的显示字段


<directive-name data-source="data" list-filed="name"></directive-name>
app.module('app').directive('directiveName', function() {
    return {
        link: function(scope, element, attrs) {
            var data = scope[attrs['source']];
            var name= attrs['listField'];
            if(angular.isArray(data))
            {
                angular.forEach(data, function(item) {
                    console.log(item[name]);
                })
            }
        },
        template: '',
        restrict: 'E' 
    }
})

给特定的显示字段添加过滤器所引起的问题


app.module('app').directive('directiveName', function() {
    return {
        link: function(scope, element, attrs) {
            var data = scope[attrs['source']];
            var expression= attrs['listField'];
            if(angular.isArray(data))
            {
                angular.forEach(data, function(item) { 
                    console.log(scope.$eval(expression, item));
                })
            }
        },
        template: '',
        restrict: 'E' 
    } 
})
上一篇 下一篇

猜你喜欢

热点阅读