当我在投资组合中选择一个项目时,我的路线为/portfolio/:workName。在控制器中,我想将$scope.work设置为基于workName选择的任何项目。这是我到目前为止的内容:

app.factory('Works', function(){

var Works = {}

Works.projects =[
    {
        name : "ProjectOne",
        string : "stuff",
    {
        name : "ProjectTwo",
        string : "more stuff",
    },
    {
        name : "ProjectThree",
        string : "stuff",
    }
];

Works.findByName = function(name) {
    Works.projects.forEach(function(work) {
        if(work.name == name) {
            return work;
        }
    });
}
return Works;
})

app.controller("ProjectController", function ($scope, Works, $routeParams) {
$scope.work = Works.findByName($routeParams.workName);
});


但是,在调试器中,尽管$routeParams.workName返回“ ProjectOne”,但Works.findByName($routeParams.workName)返回未定义。

最佳答案

代码的问题是forEachnot returning a value(您也不会在findByName方法和the return value of forEach is undefined中返回结果),而只是执行比较。您可以按以下方式修改方法或使用filter()方法(以Works.findByNameUsingFilter为例):



angular.module('myApp', [])
.factory('Works', [function(){
    var Works = {};
    Works.projects = [
        {
            name: "ProjectOne",
            string: "stuff1"
        },
        {
            name : "ProjectTwo",
            string : "more stuff",
        },
        {
            name : "ProjectThree",
            string : "stuff",
        }
    ];

    Works.findByName = function(name) {
        var res = '';
        Works.projects.forEach(function(work) {
            if(work.name === name) {
                res = work;
            }
        });
        return res;
    };

    Works.findByNameUsingFilter = function(name) {
        return Works.projects.filter(function(work) {
            return work.name === name;
        });
    };

    return Works;
}])
.controller("ProjectController", ['$scope', 'Works', function ($scope, Works) {
    $scope.workUsingFindByName = Works.findByName("ProjectOne");
    $scope.workUsingFindByNameUsingFilter = Works.findByNameUsingFilter("ProjectThree");
}]);

<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="ProjectController">
  {{workUsingFindByName.string}}
  <br/>
  {{workUsingFindByNameUsingFilter[0]}}
  </div>
</div>

关于javascript - 在Angular Factory中按属性获取元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45106395/

10-12 01:00