2017-08-10 70 views
0

有没有办法在AngularJS模板中添加一个新的作用域?在AngularJS模板中创建新范围?

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

基本上按钮将有一个“活动”状态或“非活动”状态。

在'激活'时,修饰符会增加,'非激活'时它会恢复正常。

但是让我们说我有100个这些按钮。我可以使修饰符-1,修饰符-2等变量,但这不是最佳实践。

如何在此模板中创建一个新范围,以便我可以在整个100个按钮中将修饰符保留为变量名称?

+0

在每个按键事件或相同的每个变量deffernt? –

+0

修改器对于每个按钮 –

+0

都不相同,您可以在'ng-repeat'循环中创建它们。 –

回答

0

我的理解是所有按钮的范围需要相同,所以我建议下面的代码,如果代码片段正确使用它来构建代码,那么指令包含一个隔离范围,以便控制器变量不会影响指令变量,修饰符和某些值的值会写入指令中,如果您希望从控制器传递该变量,则可以通过范围传递变量。参考: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){ 
 
     \t scope.somevalue = 100; 
 
      scope.modifier = {value:32, state: 'active'}; 
 
      scope.output = scope.somevalue - scope.modifier.value; 
 
      console.log(scope.output); 
 
      scope.modifiertoggle = function(){ 
 
      \t scope.modifier.state = scope.modifier.state === 'active' ? 'inactive' : 'active'; 
 
      if(scope.modifier.state === 'active'){ 
 
      \t \t scope.output = scope.somevalue - scope.modifier.value; 
 
      }else{ 
 
      \t \t 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>