需要在angularjs中动态创建函数

时间:2016-04-13 12:56:00

标签: javascript angularjs

我需要在angularjs中创建一个新函数,所以我做了类似下面的事情。我需要在angular tree control中禁用一些元素。

$scope.filterTreeOption = {
    dirSelectable: false,
    multiSelection: true,
    injectClasses: {
      "li": "injectedTreeLi"
    }
}

$scope.isFatalDisabled = false; $scope.isErrorDisabled = false; $scope.isWarnDisabled = false; $scope.isInfoDisabled = false; $scope.isDebugDisabled = false; $scope.isTomcatDisabled = false; $scope.isAgentDisabled = false; $scope.isSessionDisabled = false; $scope.isActivityDisabled = false;

// Another function here which changes above boolean property to true if needed.

var func = function(node) {
  var tmp = (node.label.indexOf("Fatal") !== 0 && $scope.isFatalDisabled) &&
  (node.label.indexOf("Error") !== 0 && $scope.isErrorDisabled) &&
  (node.label.indexOf("Warn") !== 0 && $scope.isWarnDisabled) &&
  (node.label.indexOf("Info") !== 0 && $scope.isInfoDisabled) &&
  (node.label.indexOf("Debug") !== 0 && $scope.isDebugDisabled) &&

  (node.label.indexOf("Tomcat") !== 0 && $scope.isTomcatDisabled) &&
  (node.label.indexOf("Agent") !== 0 && $scope.isAgentDisabled) &&
  (node.label.indexOf("Session") !== 0 && $scope.isSessionDisabled) &&
  (node.label.indexOf("Activity") !== 0 && $scope.isActivityDisabled);
  return tmp;
}

//and then I am trying to assign it to an already existing javascript object

$scope.filterTreeOption.isSelectable = func;

但这不会生效。这是正确的方式还是我错过了什么。请帮忙。

1 个答案:

答案 0 :(得分:1)

您应该针对indexOf检查的值不是0,这是字符串的第一个索引,但是-1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

$scope.filterTreeOption = {
    dirSelectable: false,
    multiSelection: true,
    injectClasses: {
      "li": "injectedTreeLi"
    }
}

$scope.isFatalDisabled = false; $scope.isErrorDisabled = false; $scope.isWarnDisabled = false; $scope.isInfoDisabled = false; $scope.isDebugDisabled = false; $scope.isTomcatDisabled = false; $scope.isAgentDisabled = false; $scope.isSessionDisabled = false; $scope.isActivityDisabled = false;

// Another function here which changes above boolean property to true if needed.

var func = function(node) {
  var tmp = (node.label.indexOf("Fatal") !== -1 && $scope.isFatalDisabled) &&
  (node.label.indexOf("Error") !== -1 && $scope.isErrorDisabled) &&
  (node.label.indexOf("Warn") !== -1 && $scope.isWarnDisabled) &&
  (node.label.indexOf("Info") !== -1 && $scope.isInfoDisabled) &&
  (node.label.indexOf("Debug") !== -1 && $scope.isDebugDisabled) &&

  (node.label.indexOf("Tomcat") !== -1 && $scope.isTomcatDisabled) &&
  (node.label.indexOf("Agent") !== -1 && $scope.isAgentDisabled) &&
  (node.label.indexOf("Session") !== -1 && $scope.isSessionDisabled) &&
  (node.label.indexOf("Activity") !== -1 && $scope.isActivityDisabled);
  return tmp;
}

//and then I am trying to assign it to an already existing javascript object

$scope.filterTreeOption.isSelectable = func;