angularjs从属性生成字符串

时间:2016-04-22 09:25:16

标签: javascript angularjs

我正在开发一个小项目,根据激活的类(对象)生成字符串。我希望它的工作方式有点像这样:

  

for(i< = 30)if(obj [$ i] == isActive)?string =" x = 1":string =" x = 0&#34 ;; echo x;

现在我有控制器,如果单击对象,则启用和禁用类。如何根据启用了某些类的对象生成字符串?得到像x = 1& y = 0& z = 0& xyz = 1的结果。由于某种原因,它不是为我更新



var classApp = angular.module('classApp', []);
classApp.controller('classCtrl', function ($scope) {
	$scope.isActive1 = false;
	$scope.isActive2 = false;
	var build = "";
	if($scope.isActive1==true?build="x=1&":build="x=0&");
	$scope.link = build;
});

body {
  background: #fff;
  -webkit-font-smoothing: antialiased;
  padding: 40px;
  text-align: center;
}
.active {
	-webkit-filter: grayscale(0%);
    filter: grayscale(0%);
}
img {
	-webkit-filter: grayscale(100%);
    filter: grayscale(100%);
  width: 128px;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="classApp" ng-controller="classCtrl">
  <img src="http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/sign-check-icon.png" ng-class="{'active': isActive1}" ng-click="isActive1 = !isActive1"/> 
  <img src="http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/sign-check-icon.png" ng-class="{'active': isActive2}" ng-click="isActive2 = !isActive2"/>
  test={{link}}
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您需要告诉angulajs $ scope已更改,您只在控制器中设置一次。需要使用$ watch概念每次更新。

var classApp = angular.module('classApp', []);
classApp.controller('classCtrl', function ($scope) {
	$scope.isActive1 = false;
	$scope.isActive2 = false;
	var build = "";
	
    $scope.$watch('isActive1', function(newValue) {
      if(newValue==true?build="x=1&":build="x=0&");
	         $scope.link = build;
    });
});
body {
  background: #fff;
  -webkit-font-smoothing: antialiased;
  padding: 40px;
  text-align: center;
}
.active {
	-webkit-filter: grayscale(0%);
    filter: grayscale(0%);
}
img {
	-webkit-filter: grayscale(100%);
    filter: grayscale(100%);
  width: 128px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="classApp" ng-controller="classCtrl">
  <img src="http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/sign-check-icon.png" ng-class="{'active': isActive1}" ng-click="isActive1 = !isActive1"/> 
  <img src="http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/sign-check-icon.png" ng-class="{'active': isActive2}" ng-click="isActive2 = !isActive2"/>
  test={{link}}
</div>