0

Is there a way to add a new scope in an AngularJS template?

<button ng-click="modifier + 1 if inactive or modifier - 1 if inactive">{{someNumber + modifier}}</button>

Basically the button will have an 'active' state or 'inactive' state.

On 'active', the modifier will increase, on 'inactive' it will go back to normal.

But let's say I have 100 of these buttons. I can make variables like modifier-1, modifier-2,.... but that's not best practice.

How do I make a new scope within this template so I can keep modifier as a variable name throughout the 100 buttons?

S Jung
  • 160
  • 9

1 Answers1

0

from your question I understand that the scope needs be same for all the buttons, so I suggest the below code, if the snippet is correct use it to build you code, the directive contains an isolated scope so that the controller variable does not affect the directive variable and the values for modifier and somevalue are written inside the directive, if you want this to pass from the controller, pass the variables through the scope. refer: pass variable from controller to directive

    var myApp = angular.module('myApp', []);
    
    myApp.controller('MyController', ['$scope', function ($scope) {
        $scope.items = [{
            salutation: 'Hello',
            name: 'World'
        }, {
            salutation: 'Konichiwa',
            name: 'Mr. Roboto'
        }];
         $scope.test = "nare";
    }]);

    myApp.directive('customButton', function () {
    return {
        restrict: "E",
        scope: {},
        template: '<button ng-repeat="x in [].constructor(100) track by $index" ng-click="modifiertoggle()">{{output}}</button>',
        link: function(scope, element, attrs){
         scope.somevalue = 100;
          scope.modifier = {value:32, state: 'active'};
          scope.output = scope.somevalue - scope.modifier.value;
          console.log(scope.output);
          scope.modifiertoggle = function(){
           scope.modifier.state = scope.modifier.state === 'active' ? 'inactive' : 'active';
            if(scope.modifier.state === 'active'){
            scope.output = scope.somevalue - scope.modifier.value;
            }else{
            scope.output = scope.somevalue + scope.modifier.value;
            }
          }
        }
    };
});
button{
  height:50px;
  width:75px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller='MyController'>
    <custom-button></custom-button>
</div>
Naren Murali
  • 19,250
  • 3
  • 27
  • 54