将值从父作用域复制到指令作用域

时间:2016-06-01 20:17:06

标签: javascript angularjs angularjs-directive angularjs-scope

我是AngularJS的新手,并且想知道如何将我的父作用域中的值复制到没有绑定的指令作用域(2个单独的实例)。目前我的实现按原样,我的newHostTemplate调用{{newHost.ipAddress}}但是我希望newHost来自指令范围,而不是父节点。

host.directive('newHost', function(){
    return {
        restrict: 'E',
        template: '<div ng-include="getTemplateUrl()"></div>',
        scope: true,
        link: function(scope, element, attr) {
            scope.newBox = function() {
                scope.getTemplateUrl = function() {
                    return 'hosts/newHostTemplate.html';
                }
            }
        }
    }
});

host.controller('hostsController', function($scope, $http, $window, $rootScope){
    $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
        console.log("failed to change routes");
    });

    $scope.newHost = {};
    $scope.addNewHost = function() {
        $http({
            method  : 'POST',
            url     : 'http://192.168.0.99:5000/newHost',
            data    : JSON.stringify($scope.newHost),  // pass in data as strings
        })
        .success(function(data) {
            console.log(data);
            $scope.newBox()
            $scope.newHost = {}
            //on success we want to close the modal and reset the data
            $scope.dismiss()
        });
    };
});

目前,当我运行此操作时,我收到一条错误消息,指出newBox不是函数。

1 个答案:

答案 0 :(得分:2)

您想要隔离范围。而不是范围:true ,请执行范围:{}

从父指令到指令的任何显式输入都将通过已定义的范围变量:

scope: {
    twoWayBoundInputOne: '=',
    staticStringInputTwo: '@',
    functionThree: '&'
}

此外,建议的体系结构是将可重用的代码(例如AJAX请求)放入服务中。 https://docs.angularjs.org/guide/services

以注入$ scope或$ http。

的方式将服务注入指令和控制器

您的服务可能如下所示:

/* global bz_app */
host.factory('hostsService', ['$http',
function ($http) {
    return function () {
        this.add = function () {
            return $http({
                method  : 'POST',
                url     : 'http://192.168.0.99:5000/newHost',
                data    : JSON.stringify($scope.newHost),  // pass in data as strings
            });
        };

        this.templateUrl = function() {
                return 'hosts/newHostTemplate.html';
        };
    };
}]);

// then in your controller or directive you can do this, to get an instance that doesn't get impacted by other instances.
scope.host = new HostsService();