【问题标题】:AngularJs: init directive model with parameter from UrlAngularJs:带有来自 Url 的参数的 init 指令模型
【发布时间】:2014-08-29 14:06:25
【问题描述】:

我有几个这样的特定指令实例:

<type="text" my-directive ng-model="formData.property1">
<type="text" my-directive ng-model="formData.property2">

formData.propery 是一个类似{ name: '', code: '' } 的对象。 formData.propery.name 用于视图层,formData.propery.code 作为值发送到服务器。

我想从 URL 参数初始化这些指令 - 传递代码并获取整个对象作为模型值。

这里的困难是:

  1. 我不能在指令作用域中调用函数,该函数使用特定代码从服务器获取对象,因为它违反了父作用域和指令作用域的关注点分离。

  2. 由于 $http 请求的异步调用类型,我无法从父范围初始化模型。

  3. 我不能在通过模型变量名称从服务器获取对象的指令中使用特定的 init 函数,因为它有点笨拙并且会弄乱代码。

那么什么是正确的方法呢?

示例 1:

    getObj1 = (code)->
        $http({
            url: '/api/service/GetByCode'
            method: 'POST'
            data: { code: code }
            headers: {'Content-Type': 'application/json; charset=utf-8'}
        })
        .success((data)->
            $scope.formData.property1 = angular.fromJson(data.result)
        )

    getObj2 = (code)->
        $http({
            url: '/api/service/GetByCode'
            method: 'POST'
            data: { code: code }
            headers: {'Content-Type': 'application/json; charset=utf-8'}
        })
        .success((data)->
            $scope.formData.property2 = angular.fromJson(data.result)
        )

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    好吧,我只需要将属性作为参数传递给使用闭包的函数:

       getObj = (code, prop)->
            theProp = prop
            $http({
                url: '/api/service/GetByCode'
                method: 'POST'
                data: { code: code }
                headers: {'Content-Type': 'application/json; charset=utf-8'}
            })
            .success((data)->
                theProp = angular.fromJson(data.result)
            )
    

    然后这样称呼它:

    getObj(someCode1, scope.formData.property1)
    getObj(someCode2, scope.formData.property2) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-05
      • 1970-01-01
      相关资源
      最近更新 更多