Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce redundant code using angularjs?

dt.html and st.html are exactly same only difference in controller is scoket.on call dtconsumer vs stconsumer , How can i use one controller for both views or same view and controller for two different state. there is alot of redundant code in js and html. what is best approach to resolve this issue ?

Do i need to write directive ?

dt.html

<div class="panel-body display-logs" scroll-bottom="event" style="width:100%;">
                        <ul style="list-style: none;">
                            <li ng-repeat="message in event | limitTo:1000" ng-class="{lastItem: $last}"><span>{{message.value}}</span></li>
                        </ul>
                </div>

Ctrl-1.js

var searchEnv = 'DT';
$scope.event = [];
socket.on('dtConsumer',function (data) {
        var obj = {
            file:$scope.filename,
            data:data
        }
        var messageSize = getBytesForBuffer(data);
       $scope.event.push(data);
    });

Ctrl-2.js

var searchEnv = 'st';
$scope.event = [];
socket.on('StConsumer',function (data) {
        var obj = {
            file:$scope.filename,
            data:data
        }
       $scope.event.push(data);
        var messageSize = getBytesForBuffer(data);
    });

app.js

.state('app.dt', {
        url: '/dt',
        templateUrl: 'view/partials/dt.html',
        controller: 'DitCtrl'
    })
    .state('app.st',{
        url:'/st',
        templateUrl:'view/partials/st.html',
        controller:'StCtrl'
    })
like image 586
hussain Avatar asked Sep 25 '26 10:09

hussain


1 Answers

You could pass dt/st via $stateParams, so you could keep 1 url with dt/st as a parameter. Something like this.

app.js

.state('app.dt', {
    url: '/:type',
    templateUrl: 'view/partials/dt.html',
    controller: 'DitCtrl'
})

ctrl.js

var searchEnv = $stateParams.type;
$scope.event = [];
socket.on(searchEnv+'Consumer',function (data) {
    var obj = {
        file:$scope.filename,
        data:data
    }
    var messageSize = getBytesForBuffer(data);
   $scope.event.push(data);
});
like image 125
tomek550 Avatar answered Sep 28 '26 00:09

tomek550



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!