Вопрос

I have two sections of a page that contain a form that are nearly identical. The only difference is some of the wording and the values of an object in the parent scope. How can I tell the view or the controller to use one scope variable instead of another?

Contrived Example:

myApp.controller('ParentController', function($scope) {
    $scope.container = {
        someA: { a: 1, b: 3 },
        someB: { a: 2, b: 4 }
    }
});

myApp.controller('ChildController', function($scope) {
    // Some scope variable that gets the value of container.someA
    // or container.someB

    $scope.result = $scope.someValue.a + $scope.someValue.b;
});

I could then use $scope.result in two child views that use the same template.

<div ng-controller="ParentController">
   <!-- Include #1 -->
   <div ng-include="someTemplate.html" ng-controller="ChildController"></div>
   <!-- Include #2 -->
   <div ng-include="someTemplate.html" ng-controller="ChildController"></div>
</div>

How can I tell include #1 to use the values of $scope.container.someA and include #2 to use the values of $scope.container.someB?

Это было полезно?

Решение

This is a typical case for a directive.

app.directive("name", function() {
    return {
        restrict: "A",
        templateUrl: "someTemplate.html",
        scope: {
            someValue: "="
        },
        controller: function($scope) {
            $scope.result = $scope.someValue.a + $scope.someValue.b;
        }
    };
});

Use it as:

<div ng-controller="ParentController">
    <!-- Include #1 -->
    <div my-template some-value="container.someA"></div>
    <!-- Include #2 -->
    <div my-template some-value="container.someB"></div>
</div>

You will have to pay attention to the isolated scope, it does NOT inherit stuff from the parent scope; therefore you will have to pass any data that you want in the directive, just like the scope: { someValue: "=" }.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top