How can I reduce redundant code using angularjs?

dt.html

and the st.html

exact same difference in the scoket.on

call dtconsumer

vs controller stconsumer

. How can I use one controller for both views, or one view and controller for two different states. in js

and html

there is a lot of redundant code. what is the best way to solve this problem?

Do I need to write a 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'
    })

      

+3


source to share


1 answer


You can pass dt / st through $stateParams

so you can store 1 url with dt / st as parameter. Something like that.

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);
});

      

+1


source







All Articles