如何将单选按钮中的ng-model值从ng-repeat传递到指令上的link函数

时间:2016-08-29 15:21:17

标签: angularjs angularjs-directive angularjs-scope

我想在页面加载后选择Radio Button中的一个,从stackoverflow上的另一个问题我发现Radio Button将检查输入属性的值是否等于值适用于Radio Button的模型。但我无法在child指令内的link函数中访问$parent.selectedItem上的模型(Radio Button)。我在示例中使用的Api是一个占位符,但实时我将选择一个属性true/false,我想绑定到$parent.selectedItem

var mainApp = angular.module('mainApp', []);

mainApp.factory('myFactory', function ($http) {
    var myFactory = {
        myMethod: function () {
            var promise = $http.get('https://jsonplaceholder.typicode.com/users').then(function (response) {

                return response.data;

            });
            return promise;
        }
    };
    return myFactory;
});

控制器:

mainApp.controller('myController', function ($scope, myFactory) {
    myFactory.myMethod().then(function (result) {
        $scope.data = result
    })
});

指令:

mainApp.directive('parent', function (myFactory) {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        templateUrl: 'parent.html',
        link: function (scope, element, attrs, ctrl) {
            myFactory.myMethod().then(function (result) {
                scope.Model = result
            })

        }
    }
});
mainApp.directive('child', function () {
    return {
        restrict: 'E',
        scope: {
            Model: '=ngModel'
        },
        replace: true,
        require: 'ngModel',
        templateUrl: 'child.html',
        link: function (scope, element, attrs, ctrl) {
            // unable to access scope.selectedItem
            console.log(scope.selectedItem) 
        }
    }
});

HTML:

   // mainpage.html
   <body ng-app="mainApp"><parent></parent></body>

   //parent.html
     <div><child ng-model = "Model"></child></div>

   //child.html
     <div ng-repeat="item in Model"><input type="radio" name="itemSelected"
     ng-value="item" ng-model="$parent.selectedItem"/>{{item.name}}</div>

1 个答案:

答案 0 :(得分:1)

当你在子指令中需要ngModel时,你基本上需要的是它的控制器,然后将这个控制器作为第4个参数注入你的链接函数,在你的情况下是ctrl参数

所以现在你的ngModel可能有效,但它不在你的链接函数中,因为你希望它作为selectedItem存在于作用域上,但是在你的作用域上你已经将它声明为Model(不是selectedItem) )。但是,您还可以访问ngModel控制器,因此您可以通过其控制器询问其值:https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

例如:

ctrl.$viewValue
// or
ctrl.$modelValue
//whichever serves your purpose